<template>
  <div class="div_main">
    <div class="div_table">
      <div class="div_btn">
        <div class="div_btn_left">

          <el-upload :headers="$getElUploadHeaders()"
                     ref="upload"
                     class="upload-btn"
                     action="uploadUlr"
                     :limit="1"
                     :accept="'.xls,.xlsx'"
                     :with-credentials="true"
                     :show-file-list="false"
                     :auto-upload="true"
                     :on-progress="handleProgress"
                     :on-success="handleExcelSuccess"
                     :before-upload="beforeExcelUpload"
                     :http-request="uploadHttpRequest">
            <el-button size="small"
                       class="diy-button--white"
                       :loading="importLoading">表格导入</el-button>
          </el-upload>
          <el-button class="diy-button--white"
                     size="small"
                     style="margin-left:10px"
                     @click="handleExportModule()">下载模板</el-button>

        </div>
      </div>
      <el-table ref="ref_table"
                :data="dataList"
                border
                :height="tableHeight"
                class="div_table_item"
                v-loading="dataListLoading"
                style="width: 100%">
        <el-table-column label="序号"
                         header-align="center"
                         align="center"
                         type="index"
                         width="100"></el-table-column>

        <el-table-column prop="deptName"
                         header-align="center"
                         align="center"
                         label="表格信息"
                         min-width="100">
        </el-table-column>
        <el-table-column prop="dataName"
                         header-align="center"
                         align="center"
                         label="平台对应信息"
                         min-width="110">
          <template slot-scope="scope">

            <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)"
                         :key="item.id"
                         :label="item.label"
                         :value="item.id">
              </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.itemId">
              </el-option>
            </el-select>

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

      </el-table>
      <div>
        <el-pagination @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page.sync="pageNo"
                       :page-sizes="[20, 50, 100, 200]"
                       :page-size="pageSize"
                       layout="sizes, prev, pager, next, total"
                       :total="total">
        </el-pagination>
      </div>

      <div ref="divEditBtn"
           class="div_edit_btn">

        <el-button type="primary"
                   size="small"
                   class="diy-button--blue"
                   @click="handleComfirm">保 存</el-button>
      </div>

    </div>

    <!-- 修改弹出框 -->
    <el-dialog :visible.sync="formShow"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               :title="'数据更新配置'"
               width="850px"
               top="5vh"
               class="dialog-h"
               @closed="diaClose">
      <div class="div_form">
        <el-form ref="ref_form"
                 :inline="true"
                 :model="formData">

          <el-form-item label="适用范围"
                        label-width="150px"
                        style="display: block">

          </el-form-item>

        </el-form>
      </div>

      <div class="div-btn">
        <el-button size="small"
                   @click="diaClose">取 消</el-button>
        <el-button size="small"
                   type="primary"
                   @click="editDiaOK">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import { requestPost } from '@/js/dai/request'

import { mapGetters } from 'vuex'
export default {

  data () {
    return {
      customerId: '', // 客户id，父组件传
      customerName: '', // 客户名称，父组件传

      tableParams: {
        customerId: ''
      },
      // tableHeight: 500,
      search: '',
      dataList: [],

      dataListLoading: false,
      total: 0,
      pageSize: 20,
      pageNo: 0,


      formShow: false,
      formData: {},

      scopeList: [],
      dataSyncConfigId: '',
      importLoading: false,

      groupList: [],
      sHeight: 0,
    }
  },

  computed: {
    tableHeight () {
      const h = this.clientHeight - this.sHeight + this.iframeHeigh
      const _h = this.clientHeight - this.sHeight
      return this.$store.state.inIframe ? h : _h
    },

    ...mapGetters(['clientHeight', 'iframeHeight'])
  },
  components: {

  },
  created () {

  },
  async mounted () {
    await this.loadData()
    await this.loadPersonGroup()

    this.sHeight = this.$refs.divEditBtn.offsetHeight + 300
  },
  methods: {


    diaClose () {
      this.formShow = false
    },

    async loadPersonGroup () {
      const url = '/oper/customize/icformitemgroup/list'
      // const url = 'http://yapi.elinkservice.cn/mock/245/gov/org/isServiceProject/service/serviceScopeTree'
      let params = {
        formCode: 'resi_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, isSet) {
      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]
        oneData.itemList = data
        this.$set(this.dataList, index, oneData)
      } else {
        this.$message.error(msg)
      }
    },

    // 加载列表数据
    async loadData () {
      this.dataListLoading = true
      // const url = 'http://yapi.elinkservice.cn/mock/245/epmetuser/dataSyncConfig/list'
      const url = '/epmetuser/dataSyncConfig/list'

      this.tableParams = {
        pageSize: this.pageSize,
        pageNo: this.pageNo
      }

      const { data, code, msg } = await requestPost(url, this.tableParams)
      this.dataListLoading = false
      if (code === 0) {
        this.total = data.total
        this.dataList = data.list
        this.dataList.forEach(element => {

          element.stateShow = element.switchStatus === 'open' ? true : false

        })
      } else {
        // this.$message.error(msg )
      }
    },

    handleChangeScope (value) {
      // console.log('value', value)

      this.orgIdArray = value
      this.scopeList = []
      let selArray = this.$refs["myCascader"].getCheckedNodes()

      // console.log('selArray', selArray)

      selArray.forEach((element, index) => {

        let obj = {
          orgId: element.data.agencyId,
          orgType: element.data.level,
          orgIdPath: element.path.join(':'),

        }
        this.scopeList.push(obj)
      });

      console.log('this.scopeList', this.scopeList)

    },

    handleComfirm () {
      console.log(this.dataList)
    },

    async editDiaOK () {
      // const url = 'http://yapi.elinkservice.cn/mock/245/epmetuser/dataSyncConfig/scopeSave'
      const url = '/epmetuser/dataSyncConfig/scopeSave'

      let params = {
        dataSyncConfigId: this.dataSyncConfigId,
        scopeList: this.scopeList
      }

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

      if (code === 0) {
        this.formShow = false
        this.loadData()
      } else {
        // this.$message.error(msg )
      }
    },

    async handleExportModule () {
      let url = "/heart/iccommunityselforganization/import-template-download";

      let params = {};
      await this.$http({
        method: "POST",
        url,
        responseType: "blob",
        data: params,
      })
        .then((res) => {
          // this.download(res.data, title + '.xls')
          if (res.headers["content-disposition"]) {
            let fileName = window.decodeURI(
              res.headers["content-disposition"].split(";")[1].split("=")[1]
            );
            console.log("filename", fileName);
            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", err);
          return this.$message.error("网络错误");
        });
    },
    // 上传大图标成功
    handleExcelSuccess (res, file) {
      if (res.code === 0 && res.msg === "success") {
        console.log("resss---ppp", res);
      } else {
        this.$message.error(res.msg);
      }
    },
    handleProgress (event, file, fileList) {
      console.log("percentage", file.percentage);
    },

    beforeExcelUpload (file) {
      console.log("file", file);
      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 < 10;
      if (!fileType) {
        this.$message.error("上传文件只能是xls/xlsx格式！");
      }

      if (!isLt1M) {
        this.$message.error("上传文件大小不能超过 10MB!");
      }
      return fileType && isLt1M;
    },
    async uploadHttpRequest (file) {
      this.importLoading = true;
      this.importBtnTitle = "正在上传中...";
      this.$message({
        showClose: true,
        message: "导入中，请到系统管理-导入记录中查看进度",
        duration: 0,
      });
      const formData = new FormData(); //FormData对象，添加参数只能通过append('key', value)的形式添加
      formData.append("file", file.file); //添加文件对象
      await this.$http
        .post(
          "/heart/iccommunityselforganization/importcommunityselforganization",
          formData
        )
        .then((res) => {
          console.log("res-up", res);
          if (res.data.code == 0 && res.data.msg == "success") {
            // this.$message.success('导入成功')
            this.getTableData();
          } else this.$message.error(res.data.msg);
        })
        .catch((err) => {
          console.log("失败", err);
          file.onError(); //上传失败的文件会从文件列表中删除
          // this.$message.error('导入失败')
        });
      // axios({
      //   url:
      //     window.SITE_CONFIG["apiURL"] +
      //     "/heart/iccommunityselforganization/importcommunityselforganization",
      //   method: "post",
      //   data: formData,
      //   // responseType: "blob",
      // })
      //   .then((res) => {
      //     this.importLoading = false;
      //     this.importBtnTitle = "导入";
      //     console.log("resresresresresresres", res);

      //     this.getTableData();
      //     if (res.data.code == 0) {
      //       return this.$message.success(res.data.data || "导入成功");
      //     } else {
      //       return this.$message.error(res.data.msg);
      //     }
      //   })
      //   .catch((err) => {
      //     console.log("失败", err);
      //   });
      this.importLoading = false;
      this.importBtnTitle = "导入";
      this.$refs.upload.clearFiles();
    },

    handleSizeChange (val) {
      this.pageSize = val
      this.pageNo = 1
      this.loadData()
    },
    handleCurrentChange (val) {
      this.pageNo = val
      this.loadData()
    },

    // 取消
    diaCancel () {
      this.$emit('cancleBack')
    },


  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/scss/modules/management/list-main.scss";

.div_edit_btn {
  display: flex;
  margin-top: 20px;
  margin-right: 16px;
  justify-content: flex-end;
  text-align: center;
}

.item_width_sel {
  width: 200px;
}
</style>
