<template>
  <div class="m-detail-main" v-loading="dataListLoading">
    <div class="steps1">
      <el-steps :active="progress">
        <el-step :class="[this.operatorName == null ? 'showNum' : '']" title="选择数据源"
          :description="`${this.operatorName}(${this.createdTime})`"></el-step>
        <el-step title="智能填表设置" :class="[this.progress == 2 || this.progress == 3 ? '' : 'showNum']"></el-step>
        <el-step title="数据填充范围"></el-step>
      </el-steps>
    </div>
    <div v-show="progress == 1" style="width: 80%; margin-top: 10px; font-size: 16px;">
      <div class="flex"  style="margin: 60px 0;">
        <div @click="onClickTab(item)" class="flex"
          style=" cursor: pointer;  position: relative;display: flex; flex-direction: column; align-items: center; justify-content: center; width: 155px;height: 90px;background: #F1F4FA;border-radius: 4px; margin-left: 60px;"
          v-for="(item, index) in dataSourceList">
          <img style="width: 30px; height: 30px;" :src="item.image" alt="">
          <span style="margin-top: 10px;">{{ item.name }}</span>
          <img v-if="item.status" style="width: 30px; height: 30px;position: absolute; top: 0;right: 0;"
            src="@/assets/images/index/select.png" alt="">
          <img v-if="!item.status" style="width: 30px; height: 30px;position: absolute; top: 0;right: 0;"
            src="@/assets/images/index/notselect.png" alt="">
        </div>
      </div>
    </div>
    <div v-show="dataList.length > 0 && progress == 2" style="height: 600px; overflow-y: scroll;margin: 60px 0;">
      <el-table ref="ref_table" :data="dataList" border class="m-table-item" style="width: 100%">
        <el-table-column label="序号" header-align="center" align="center" type="index" width="100"></el-table-column>
        <el-table-column prop="userTableHeader" header-align="center" align="center" label="上传表格列" min-width="60">
          <template slot-scope="scope">
            <span :class="[
              scope.row.itemId && scope.row.itemId != ''
                ? ''
                : 'font_color_red',
            ]">{{ scope.row.userTableHeader || "--" }}</span>
          </template>
        </el-table-column>
        <el-table-column header-align="center" align="center" label="对应到" min-width="30">
          <template slot-scope="scope"><span v-if="scope.row.itemId"> =></span> </template>
        </el-table-column>
        <el-table-column prop="itemGroupId" header-align="center" align="center" label="系统字段" min-width="110">
          <template slot-scope="scope">
            <div>
              <el-select class="item_width_sel" v-model.trim="scope.row.itemGroupId" size="small" placeholder="请选择">
                <el-option v-for="item in groupList" @click.native="handleSelGroup(scope.$index, item, 'change')"
                  :key="item.fileModeCode" :label="item.fileModeName" :value="item.fileModeName">
                </el-option>
              </el-select>
              <el-select class="item_width_sel" v-model.trim="scope.row.itemId" size="small" style="margin-left: 10px"
                placeholder="请选择">
                <el-option v-for="item in scope.row.itemList" :key="item.itemId" :label="item.columnName"
                  :value="item.columnName">
                </el-option>
              </el-select>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-show="progress == 3" style="height: 600px; overflow-y: scroll;margin: 60px 0;">
      <div v-if="formData1.importCategory === 'BASEINFO'">
        <resi-search ref="resi_form"></resi-search>
      </div>
      <div v-else>
        <HoseSearch ref="house_form"/>
      </div>
    </div>
    <div>
      <span slot="footer" style="margin-top: 30px; display: flex; justify-content: flex-end;">
      <el-button v-if="progress != 1" @click="progress = progress - 1">上一步</el-button>
      <el-button type="primary" @click="onClickNext()" >下一步</el-button>
    </span>
    </div>

  </div>
</template>
<script>
import { requestPost } from "@/js/dai/request";
import resiSearch from "../../../../components/resiSearch.vue";
import HoseSearch from "./hose-search.vue";
import { Loading } from "element-ui";
export default {
  data() {
    return {
      dataList: [],
      progress: 1,
      fileCode: null,
      progressNum: null,
      createdTime: null,
      operatorName: null,
      formData1: {
        id: 0,
        name: "楼栋房屋信息一张表",
        image: "https://elink-esua-epdc.oss-cn-qingdao.aliyuncs.com/epmet-saas/dev/internal/20250114/003b8782213a487b8ce7d4267262d0ec.png",
        status: 1,
        importCategory: "BASEINFO",
        originalFilePath: "https://elink-esua-epdc.oss-cn-qingdao.aliyuncs.com/epmet-saas/dev/20250115/c4102136584140aeaf323767361a1e92.xls"
      },
      dataSourceList: [
        {
          id: 1,
          name: "居民信息一张表",
          image: "https://elink-esua-epdc.oss-cn-qingdao.aliyuncs.com/epmet-saas/dev/internal/20250114/0c1e1ea17f8842e49bf5f1afeac72e42.png",
          status: 1,
          importCategory: "HOUSE_INFO",
          originalFilePath: "https://elink-esua-epdc.oss-cn-qingdao.aliyuncs.com/epmet-saas/dev/20250115/1acd160dd0fe41409cddd461b4eb0328.xls"
        },
        {
          id: 0,
          name: "楼栋房屋信息一张表",
          image: "https://elink-esua-epdc.oss-cn-qingdao.aliyuncs.com/epmet-saas/dev/internal/20250114/003b8782213a487b8ce7d4267262d0ec.png",
          status: 0,
          importCategory: "BASEINFO",
          originalFilePath: "https://elink-esua-epdc.oss-cn-qingdao.aliyuncs.com/epmet-saas/dev/20250115/c4102136584140aeaf323767361a1e92.xls"
        },
        // {
        //   id:2,
        //   name:"单位信息一张表",
        //   image:"https://elink-esua-epdc.oss-cn-qingdao.aliyuncs.com/epmet-saas/dev/internal/20250114/211af7c657c9409fbccd11185edf0474.png",
        //   status:0
        // },
        // {
        //   id:3,
        //   name:"车辆信息一张表",
        //   image:"https://elink-esua-epdc.oss-cn-qingdao.aliyuncs.com/epmet-saas/dev/internal/20250114/bc3e4b1e89e84ed7bc31eb90bba6cbd6.png",
        //   status:0
        // },
      ],
      formData: {
        columnMateJson: '',
        searchForm: {},
        formCode:''
      },
      resident_category_import_list: [],
      groupList: [],
      fileCode: null,
      dataList: [],
      dataListLoading:false
    };
  },
  props: {
    fileCodeRow: {
      type: String,
      default: null,
    },
    taskId: {
      type: String,
      default: null,
    },
    processStatus: {
      type: String,
      default: null,
    },
    currentTable: {
      type: Array,
      default: () => []
    },
  },
  created() {
    this.loadPersonGroup();

  },
  methods: {
    onClickTab(value) {
      this.formData1 = {}
      this.dataSourceList.filter(item => item.status === 1).forEach(item => {
        item.status = 0;
      });
      this.dataSourceList.filter(item1 => item1.id === value.id).forEach(item2 => {
        item2.status = 1;
      },
        this.formData1 = this.dataSourceList[value.id],
        this.formData.formCode = this.dataSourceList[value.id].importCategory
      );
    },
    onClickNext() {
      if (this.progress === 1) {
        this.dataListLoading = true;
        this.progress = 2;
        this.checkExtractExcelHead()
      } else if (this.progress === 2) {
        let obj = this.dataList.reduce((acc, item) => {
          if (item.userTableHeader) {
            acc[item.userTableHeader] = item.itemId;
          }
          return acc;
        }, {});
        this.formData.columnMateJson = JSON.stringify(obj)
        this.progress = 3;
      } else {
        this.dataListLoading = true;
        if(this.formData1.importCategory === 'BASEINFO'){
          this.formData.searchForm= this.$refs['resi_form'].form;
        }else{
          this.formData.searchForm= this.$refs['house_form'].form;
        }
        this.saveUploadForm()
      }
    },
    async saveUploadForm() {
      const url = '/actual/base/residentBaseInfo/exportOneSheet'
      const { data, code, msg } = await requestPost(url, this.formData)
      if (code === 0) {
        this.dataListLoading = false;
        this.$emit('handleUploadDataHide',data)
      } else {
        console.log(msg);
      }
    },
    async loadPersonGroup() {
      const url = "/oper/customize/fileModeColumns/listModule";
      // const url = 'http://yapi.elinkservice.cn/mock/245/gov/org/isServiceProject/service/serviceScopeTree'
      const { data, code, msg } = await requestPost(url);
      if (code === 0) {
        this.groupList = data;
      } else {
        this.$message.error(msg);
      }
    },
    async handleSelGroup(index, item, change) {
      const url = "/oper/customize/fileModeColumns/listField";
      // const url = 'http://yapi.elinkservice.cn/mock/245/gov/org/isServiceProject/service/serviceScopeTree'
      let params = {
        REVISION: 1010,
        fileModeCode: this.formData1.importCategory,
      };
      const { data, code, msg } = await requestPost(url, params);
      if (code === 0) {
        let oneData = this.dataList[index];
        if (change == "change") {
          this.dataList[index].itemId = "";
        }
        oneData.itemList = data;
        this.$set(this.dataList, index, oneData);
      } else {
        this.$message.error(msg);
      }
    },
    async checkExtractExcelHead() {
      let columnMateStr = '';
      let foundFirstValue = false;  // 标记是否找到第一个有效值
      for (let item of this.currentTable[0].data[0]) {
          if (!foundFirstValue) {
            // 还没有遇到有效值，继续拼接空值
            if (!item || item.v === '') {
              columnMateStr += '空;';  // 空值拼接"空"
            } else {
              columnMateStr += item.v + ';';  // 第一个有效值拼接
              foundFirstValue = true;  // 标记已经找到第一个有效值
            }
          } else {
            // 遇到第一个空值时停止拼接
            if (!item || item.v === '') {
              break;  // 停止后续处理
            } else {
              columnMateStr += item.v + ';';  // 继续拼接有效值
            }
          }
      }
      // 去掉最后一个多余的分号
      columnMateStr = columnMateStr.slice(0, -1);
      const url = "/actual/base/intelligentImportData/extractImportHead";
      let params = {
        importCategory: this.formData1.importCategory,
        columnMateStr
      };
      const { data, code, msg } = await requestPost(url, params);
      if (code === 0) {
        const { metaListData, fileCode, msg } = data;
        this.dataList = metaListData;
        let groupMap = new Map(
          this.groupList.map((item) => [item.label, item])
        );
        for (let i in this.dataList) {
          this.handleSelGroup(i, groupMap.get(this.dataList[i].fileModeCode));
        }
        this.dataListLoading = false;
      } else if (code >= 8000) {
        this.$message.err(msg);
        this.dataListLoading = false;
      }
    },
    handelClickUpload(fileCode) {
      this.progress = 2;
      this.fileCode = fileCode;
    },

    successImport() {
      this.progress = 3;
      this.progressNum = 100;
    },
    updateProgress(num) {
      if (num > 100) {
        this.progress = 3;
        this.progressNum = 100;
      } else {
        this.progressNum = num;
      }
    },
    updateoperatorName({ operatorName, createdTime }) {
      this.operatorName = operatorName;
      this.createdTime = createdTime;
    },
  },
  components: {resiSearch,HoseSearch},
  computed: {},
  watch: {},
};
</script>
<style lang="scss" scoped>
@import "@/assets/scss/buttonstyle.scss";
@import "@/assets/scss/modules/management/detail-main.scss";
@import "@/assets/scss/pages/smartImport.scss";

.showUploadData {
  width: 110px;
}

.showNum {
  /deep/.el-step__description {
    display: none;
  }
}
</style>