<template>
  <div class="" v-loading="dataListLoading">
    <h3 class="title-small">基本信息</h3>
    <div class="content_box">
      <div class="left">
        <el-form :model="form" :rules="rules" ref="importForm">
          <el-form-item label="任务类型" prop="importCategory">
            <el-select
              v-model="form.importCategory"
              placeholder="请选择"
              size="small"
              class="u-item-width-normal"
            >
              <el-option
                v-for="item in resident_category_import_list"
                :label="item.label"
                :value="item.value"
                clearable
                :key="item.value"
                @click.native="handelClickCategory(item.label)"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="下载模板" prop="desc">
            <span>
              <span v-if="categoryName">{{
                this.$store.state.user.agencyName + categoryName || ""
              }}</span
              >导入模板.xlsx
              <el-button type="text" @click="handelClickDownModule"
                >点击下载</el-button
              ></span
            >
          </el-form-item>
          <el-form-item label="任务名称" prop="taskName">
            <el-input
              v-model="form.taskName"
              size="small"
              class="u-item-width-normal"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="right">
        <h4>
          <el-icon
            class="el-icon-warning-outline"
            style="color: #0056d6; font-size: 18px; font-weight: 600"
          ></el-icon>
          操作说明
        </h4>
        <p>
          1、导入数据前请先确定您的网格组织已经维护完毕。<el-button
            class="textBtn"
            type="text"
            @click="$router.push('/main/base-organization-organization')"
            >查看</el-button
          >
        </p>
        <p>2、导入房屋和居民信息前请先确保已经导入了完整的小区楼栋信息。</p>
        <p>
          3、您也可以<el-button
            class="textBtn"
            type="text"
            @click="handleExportModuleAll"
            >点击这里下载</el-button
          >全部的导入模板文件
        </p>
      </div>
    </div>
    <h3 class="title-small">上传数据</h3>
    <div class="content_box">
      <div class="left">
        <el-upload
          :headers="$getElUploadHeaders()"
          name="processFile"
          action="uploadUlr"
          :accept="'.xls,.xlsx'"
          :limit="1"
          drag
          :before-upload="beforeExcelUpload"
          :http-request="uploadHttpRequest"
          class="text-center"
          ref="upload"
        >
          <i class="el-icon-upload" style="font-size: 58px; color: #c5c9d1"></i>
          <div class="el-upload__text" v-html="$t('upload.text')"></div>
        </el-upload>
      </div>
      <div class="right">
        <p>4、上传按导入模板整理后的excel数据文件。</p>
        <p>5、文件大小不超过50M。</p>
      </div>
    </div>
    <el-row type="flex" style="margin-top: 15px">
      <el-col :span="12" align="center">
        <el-button
          style="margin-left: 10px"
          size="small"
          class="diy-button--white"
          plain
          @click="handelClickBack"
          >取消</el-button
        >
        <el-button
          class="diy-button--add"
          size="small"
          type="primary"
          @click="handelClickUpload"
        >
          开始导入</el-button
        >
      </el-col>
    </el-row>
    <el-dialog
      title="确认上传表格数据匹配关系"
      :visible.sync="dialogVisibleExtractExcelHead"
      width="75%"
    >
      <div v-if="dataList.length > 0" style="height: 600px; overflow-y: scroll">
        <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="80"
          >
            <template slot-scope="scope">
              {{ scope.row.userTableHeader || "--" }}
            </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="scope.row.itemGroupId"
                  size="small"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in groupList"
                    @click.native="handleSelGroup(scope.$index, item, 'change')"
                    :key="item.value"
                    :label="item.label"
                    :value="item.label"
                  >
                  </el-option>
                </el-select>

                <el-select
                  class="item_width_sel"
                  v-model="scope.row.itemId"
                  size="small"
                  style="margin-left: 10px"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in scope.row.itemList"
                    :key="item.itemId"
                    :label="item.label"
                    :value="item.label"
                  >
                  </el-option>
                </el-select>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleExtractExcelHead = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="dialogVisibleExtractExcelHead = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
  <script>
import { requestPost } from "@/js/dai/request";

export default {
  data() {
    return {
      form: {
        importCategory: null,
        taskName: null,
      },
      rules: {
        importCategory: [
          { required: true, message: "请选择任务类型", trigger: "change" },
        ],
        taskName: [
          { required: true, message: "请输入任务名称", trigger: "change" },
        ],
      },
      resident_category_import_list: [],
      categoryName: "",
      createdFileName: null,
      createdFileUrl: null,
      dialogVisibleExtractExcelHead: false,
      dataListLoading: false,
      dataList: [],
      groupList: [],
      fileCode:null,
    };
  },
  props: {},
  async created() {
    await this.getDictList();
    await this.loadPersonGroup();
  },
  methods: {
    async loadPersonGroup() {
      const url = "/oper/customize/icformitemgroup/list";
      // const url = 'http://yapi.elinkservice.cn/mock/245/gov/org/isServiceProject/service/serviceScopeTree'
      let params = {
        formCode: "resident_base_info",
        policyFlag: "1",
      };

      const { data, code, msg } = await requestPost(url, params);

      if (code === 0) {
        this.groupList = data;
      } else {
        this.$message.error(msg);
      }
    },
    async handleSelGroup(index, item, change) {
      const url = "/oper/customize/icformitem/getItemListV2";
      // const url = 'http://yapi.elinkservice.cn/mock/245/gov/org/isServiceProject/service/serviceScopeTree'
      let params = {
        // policyFlag: "1",
        groupId: item.id,
      };
      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);
        console.log(this.dataList);
      } else {
        this.$message.error(msg);
      }
    },
    

    handelClickCategory(label) {
      this.categoryName = label;
    },

    async checkExtractExcelHead() {
      const url = "/actual/base/intelligentImportData/extractExcelHead";
      let params = {
        originFileName: this.createdFileName,
        originalFilePath: this.createdFileUrl,
        importCategory: this.form.importCategory,
      };
      const { data, code, msg } = await requestPost(url, params);
      if (code === 0) {
        this.dialogVisibleExtractExcelHead = true;
        const { metaListData, fileCode, msg } = data;
        this.dataList = metaListData;
        this.fileCode = fileCode;
        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].itemGroupId));
        }
        this.dataListLoading = false;
      } else if (code >= 8000) {
        this.$message.err(msg);
        this.dataListLoading = false;
      }
    },
    async getDictList() {
      const url = "/sys/dict/data/dictlist";
      const { data, code, msg } = await requestPost(url, {
        dictType: "resident_category_import",
      });
      if (code === 0) {
        this.resident_category_import_list = [...data];
      } else {
        this.$message.err("字典错误");
      }
    },

    beforeExcelUpload(file) {
      this.dataListLoading = true;
      const isType = file.type === "application/vnd.ms-excel";
      const isTypeComputer =
        file.type ===
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      const fileType = isType || isTypeComputer;
      const isLt1M = file.size / 1024 / 1024 < 50;
      if (!fileType) {
        this.$message.error("上传文件只能是xls/xlsx格式！");
      }

      if (!isLt1M) {
        this.$message.error("上传文件大小不能超过 10MB!");
      }

      if (!this.form.importCategory) {
        this.$message.error("请选择导入的类别");
      }
      return fileType && isLt1M;
    },
    async uploadHttpRequest(file) {
      const formData = new FormData();
      formData.append("file", file.file);
      await this.$http
        .post("/actual/base/intelligentImportData/uploadFile", formData)
        .then((res) => {
          console.log("res-up", res);

          if (res.data.code == 0) {
            const { fileName, url } = res.data.data;
            this.createdFileName = fileName;
            this.createdFileUrl = url;
            this.checkExtractExcelHead();
          } else {
            this.$message.error(res.data.msg);
          }
        })
        .catch((err) => {
          console.log("失败", err);
          file.onError(); //上传失败的文件会从文件列表中删除
          // this.$message.error("导入失败");
        });
      this.$refs.upload.clearFiles();
    },
    // 下载全部模板
    async handleExportModuleAll() {
      let url = "/actual/base/residentBaseInfo/import/download-template";

      let params = {};
      await this.$http({
        method: "POST",
        url,
        responseType: "blob",
        data: params,
      })
        .then((res) => {
          const url = window.URL.createObjectURL(new Blob([res.data]));
          const aLink = document.createElement("a");
          aLink.style.display = "none";
          aLink.href = url;
          aLink.setAttribute("download", "人员导入模板.zip");
          document.body.appendChild(aLink);
          aLink.click();
          document.body.removeChild(aLink);
          window.URL.revokeObjectURL(url);
        })
        .catch((err) => {
          console.log("err", err);
          return this.$message.error("网络错误");
        });
    },
    // 下载单个模板
    async handelClickDownModule() {
      let url = "/actual/base/intelligentImportData/downloadImportModule";
      let params = {
        importCategory: this.form.importCategory,
      };
      await this.$http({
        method: "POST",
        url,
        responseType: "blob",
        data: params,
      })
        .then((res) => {
          if (res.headers["content-disposition"]) {
            // let fileName = window.decodeURI(
            // 	res.headers["content-disposition"]
            // 		.split(";")[1]
            // 		.split("=")[1]
            // );
            let fileName = `${
              this.$store.state.user.agencyName + this.categoryName
            }导入模板`;
            let blob = new Blob([res.data], {
              type: "application/vnd.ms-excel",
            });
            var url = window.URL.createObjectURL(blob);
            var aLink = document.createElement("a");
            aLink.style.display = "none";
            aLink.href = url;
            aLink.setAttribute("download", fileName);
            document.body.appendChild(aLink);
            aLink.click();
            document.body.removeChild(aLink); //下载完成移除元素
            window.URL.revokeObjectURL(url); //释放掉blob对象
          } else this.$message.error("下载失败");
        })
        .catch((err) => {
          console.log(err);
          return this.$message.error("网络错误");
        });
    },
    handelClickUpload() {
      this.$refs["importForm"].validate( (valid) => {
        if (valid) {
           this.saveImportResiHouseExcel()
        }
      });
    },
   async saveImportResiHouseExcel(){
      const { fileCode, dataList } = this;
      let obj = dataList.reduce((acc, item) => {
        if (item.userTableHeader) {
          acc[item.userTableHeader] = item.itemId;
        }
        return acc;
      }, {});
      const formData = new FormData();
      formData.append("columnMateJson", JSON.stringify(obj));
      formData.append("fileCode", fileCode);
      formData.append("taskName", this.form.taskName);
      await this.$http
        .post("/actual/base/intelligentImportData/importResiHouseExcel", formData)
        .then((res) => {
          console.log("res-up", res);
          if (res.data.code == 0 && res.data.msg == "success") {

            this.$emit("handelClickUpload",fileCode);
          } else this.$message.error(res.data.msg);
        })
        .catch((err) => {
          console.log("失败", err);
          file.onError();
        });
    },
    handelClickBack() {
      this.$emit("handelClickBack");
    },
  },
  components: {},
  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";
</style>
  