<template>
  <div class="">
    <slot></slot>
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="siteParams.layerName"
            placeholder="请输入站点名称"
            clearable
            prefix-icon="Search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="layerOptions"
            :props="{ label: 'label', children: 'children' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="depTreeRef"
            node-key="id"
            highlight-current
            default-expand-all
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span>
                  <el-icon color="blue" v-if="getFlagCheck(data.type)">
                    <CircleCheckFilled />
                  </el-icon>
                  <el-icon color="red" v-if="getFlagClose(data.type)"
                    ><CircleCloseFilled
                  /></el-icon>
                  <el-icon v-if="getFlagFill(data.type)"
                    ><RemoveFilled
                  /></el-icon>

                  {{ node.label }}
                </span>
              </span>
            </template>
          </el-tree>
        </div>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-descriptions class="margin-top" :column="3" border>
          <template #title>
            <div style="height: 32px; line-height: 43px">
              {{ planData.planName }}
            </div>
          </template>
          <template #extra>
            <div v-if="getApplyShow">
              <el-button
                type="danger"
                @click="rejectInfo"
                v-hasPermi="['renovation:siteIndex:reject']"
                >驳回</el-button
              >
              <el-button
                type="success"
                @click="completeInfo"
                v-hasPermi="['renovation:siteIndex:complete']"
                >通过</el-button
              >
            </div>
          </template>
          <el-descriptions-item width="10%">
            <template #label>
              <div class="cell-item">建设单位</div>
            </template>
            {{ buildInfo?.devCompany }}
          </el-descriptions-item>
          <el-descriptions-item width="10%">
            <template #label>
              <div class="cell-item">施工单位</div>
            </template>
            {{ buildInfo?.consCompany }}
          </el-descriptions-item>
          <el-descriptions-item width="10%">
            <template #label>
              <div class="cell-item">设备生产厂家</div>
            </template>
            {{ buildInfo?.manufacturer }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">施工日期</div>
            </template>
            <el-tag size="small" v-if="buildInfo?.buildDate"> {{ buildInfo?.buildDate }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">反馈图片</div>
            </template>
            <el-image
            style="width: 30px; height: 35px"
            :src="item"
            :zoom-rate="1.2"
            :max-scale="7"
            :min-scale="0.2"
             v-for="item in buildInfo?.img"
            :preview-src-list="buildInfo?.img"
            :initial-index="4"
            fit="cover"
          />
            <!-- <img style="width: 30px;height: 30px;"  src="http://localhost/src/admin/assets/logo/logo.png" v-for="item in 4" /> -->
            <!-- <img :src="item" v-for="item in buildInfo?.img" /> -->
          </el-descriptions-item>
        </el-descriptions>

        <el-table
          v-loading="loading"
          :data="renovationList"
          height="calc(100vh - 360px)"
        >
          <el-table-column
            label="改造类型"
            align="center"
            prop="renovationType"
            width="150"
          >
            <template #default="scope">
              {{ scope.row.renovationType.dictName }}
            </template>
          </el-table-column>
          <el-table-column
            label="改造内容"
            align="center"
            prop="renovationContent"
          >
            <template #default="scope">
              {{ scope.row.renovationContent.dictName }}
            </template>
          </el-table-column>
          <el-table-column
            label="整改原因"
            align="center"
            prop="renovationReason"
          >
            <template #default="scope">
              {{ scope.row.renovationReason.dictName }}
            </template>
          </el-table-column>
          <el-table-column
            label="整改方案"
            align="center"
            prop="renovationMeasure"
          >
            <template #default="scope">
              {{ scope.row.renovationMeasure.dictName }}
            </template>
          </el-table-column>
          <el-table-column label="产品名称" align="center" prop="prodName">
            <template #default="scope">
              {{ scope.row.prodInfo.prodName }}
            </template>
          </el-table-column>
          <el-table-column
            label="型号"
            show-overflow-tooltip
            align="center"
            prop="prodModel"
          >
            <template #default="scope">
              {{ scope.row.prodInfo.prodModel }}
            </template>
          </el-table-column>
          <el-table-column label="单价" align="center" prop="prodPrice">
            <template #default="scope">
              {{ scope.row.prodInfo.prodPrice }}
            </template>
          </el-table-column>

          <el-table-column
            label="操作（核对金额）"
            align="center"
            width="150"
            v-if="getPriceShow"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">

              <div v-if="reviewStatus=='2'">{{scope.row.reviewPrice}}</div>
              <div v-else>
                <el-input

                  v-model="scope.row.reviewPrice"
                  style="width: 100px"
                  placeholder="核对金额"
                  v-hasPermi="['renovation:siteIndex:price']"
                  :formatter="
                    (value) =>
                      `￥ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
                  "
                  :parser="(value) => value.replace(/\￥\s?|(,*)/g, '')"
                />

              </div>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getBuild"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="porfiles">
import { ElMessage } from "element-plus";
import {
  build,
  details,
  reject,
  complete,
  devices,
} from "@/api/system/siteplan";
import useUserStore from "@/store/modules/user";
const { proxy } = getCurrentInstance();
const props = defineProps({
  arrSite: Object,
  planData: Object,
});
console.log(props);

const planData = ref(props.planData);
const data = reactive({
  // 按钮loading
  buttonLoading: false,
  // 遮罩层
  loading: false,
  // 选中数组
  ids: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  // 显示搜索条件
  showSearch: true,
  // 总条数
  total: 0,
  // 图层管理表格数据
  dataList: [],
  planList: [],
  // 弹出层标题
  title: "",
  // 是否显示弹出层
  open: false,
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    createBy: undefined,
    layersId: undefined,
  },
  // 表单参数
  form: {},
  // 表单校验
});
const input = ref("");
const {
  open,
  showSearch,
  queryParams,
  form,
  ids,
  title,
  dataList,
  total,
  multiple,
  single,
  loading,
  planList,
  buttonLoading,
} = toRefs(data);
const planDialog = ref("测试方案1");
const applyDialog = ref(false);
const layerName = ref();
const renovationList = ref([]);

const siteParams = reactive({
  layerName: undefined,
  pageNum: 1,
  pageSize: 100,
});

const filterNode = (value, data) => {

  if (!value) return true;

  return data.label.indexOf(value) !== -1;
};

const reviewStatus = ref(-1);

// technology

const getPriceShow = ref(false);

const roles = useUserStore().roles;

//   '0':{label:'技术审核中', type:'warning'},
//   '1':{label:'财务审核中',type:'warning'},
//   '2':{label:'审核完成',type:'success'},
//   '3':{label:'驳回待修改',type:'danger'},
const getApplyShow = computed(() => {
  if (buildInfo.value?.reviewStatus == 0 && roles.indexOf("technology") != -1) {
    return true;
  }
  if (buildInfo.value?.reviewStatus == 1 && roles.indexOf("finance") != -1) {
    return true;
  }
  return false;
});

console.log(roles.indexOf("finance"));
console.log(roles.indexOf("technology"));
watch(reviewStatus, (val) => {
  if (val == 2) getPriceShow.value = true;
  else if (val == 1 && roles.indexOf("finance") != -1) {
    getPriceShow.value = true;
  }
});

const getFlagCheck = (reviewStatus) => {
  if (
    (reviewStatus == 1 && roles.indexOf("technology") != -1) ||
    reviewStatus == 2
  ) {
    return true;
  } else {
    return false;
  }
};
const getFlagClose = (reviewStatus) => {
  if (reviewStatus == 3) {
    return true;
  } else {
    return false;
  }
};
const getFlagFill = (reviewStatus) => {
  if (
    (reviewStatus == 0 && roles.indexOf("technology") != -1) ||
    (reviewStatus == 1 && roles.indexOf("finance") != -1)
  ) {
    return true;
  } else {
    return false;
  }
};
const layerOptions = ref();
const setLayerTree = (data) => {
  let parent = [
    {
      id: 0,
      label: "所有站点",
      parentId: -1,
      children: data.map((item, index) => {
        return {
          id: item.id,
          code: item.code,
          label: item.name,
          parentId: 0,
          type: item.reviewStatus,
        };
      }),
    },
  ];

  layerOptions.value = parent;
};
setLayerTree(props.arrSite);
const userData = ref([]);
const userQuery = ref([]);

const filterMethod = (query, item) => {
  return item.initial.toLowerCase().includes(query.toLowerCase());
};

const buildInfo = ref({});
/** 查询图层管理列表 */
function getBuild() {
  build({
    planId: planData.value.planId,
    deviceId: queryParams.value.deviceId,
  }).then((response) => {
    response.data.img = JSON.parse(response.data.img);
    buildInfo.value = response.data;
    reviewStatus.value = response.data.reviewStatus;
  });
}
function getDetails() {
  loading.value = true;
  details({
    planId: planData.value.planId,
    deviceId: queryParams.value.deviceId,
  }).then((response) => {
    renovationList.value = response.rows.map(item=>{
      return {
        ...item,
        reviewPrice:JSON.stringify(item.reviewPrice)=='{}'?'':item.reviewPrice
      }
    });
    total.value = response.total;
    loading.value = false;
  });
}

const handleNodeClick = (e) => {
  console.log(e);
  queryParams.value.deviceId = e.id;
  getBuild();
  getDetails();
};
const rejectInfo = () => {
  proxy.$modal
    .prompt("是否确认驳回当前站点方案,请输入驳回理由！")
    .then((e) => {
      console.log(e.value);
      return reject({
        planId: planData.value.planId,
        deviceId: queryParams.value.deviceId,
        reviewRemark: e.value,
      });
    })
    .then(async () => {
      let res = await devices({ planId: planData.value.planId });
      setLayerTree(res.data);
      getBuild();
    })
    .catch(() => {})
    .finally(() => {
      loading.value = false;
    });
};
const completeInfo = () => {
  let details=[];
  if (roles.indexOf("finance") != -1) {
    let flagIndex = -1;
    for (let i=0; i < renovationList.value.length; i++) {
      let item = renovationList.value[i];

      let reviewPrice =
        item.reviewPrice &&
        parseFloat(item.reviewPrice.replace(/\￥\s?|(,*)/g, ""));
      if (isNaN(reviewPrice)|| reviewPrice == undefined) {
        flagIndex = i + 1;
        break;
      } else {
        details.push({
          listId: item.listId,
          reviewPrice,
        });
      }
    }

    if (flagIndex != -1) {
      ElMessage({
        message: `第${flagIndex}项目填写错误，请核对`,
        type: "error",
        duration: 5 * 1000,
      });

      return;
    }
  }

  proxy.$modal
    .prompt("是否通过当前站点方案,请输入通过备注！")
    .then((e) => {
      console.log(e.value);

      return complete({
        planId: planData.value.planId,
        deviceId: queryParams.value.deviceId,
        reviewRemark: e.value,
        details,
      });
    })
    .then(async () => {
      let res = await devices({ planId: planData.value.planId });
      setLayerTree(res.data);
      getBuild();
    })
    .catch(() => {})
    .finally(() => {
      loading.value = false;
    });
};
</script>
<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: end;
}
.margin-top {
  margin-top: -45px;
}
</style>
