<template>
    <div class="g-main">
      <div>
        <div class="m-search">
          <el-form
            :inline="true"
            :model="formData"
            ref="ref_searchform"
            :label-width="'100px'"
          >
            <el-form-item label="姓名">
              <el-input
                v-model="formData.name"
                placeholder="请输入"
                size="small"
                class="u-item-width-normal"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="性别">
              <el-select
                v-model="formData.gender"
                placeholder="请输入"
                size="small"
                class="u-item-width-normal"
                clearable
              >
                <el-option
                  v-for="item in genderList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="年龄">
              <el-date-picker
                v-model="formData.birthdayStart"
                type="date"
                size="small"
                class="u-item-width-daterange"
                value-format="yyyy-MM-dd"
                placeholder="开始日期"
                :picker-options="startPickerOptions"
              >
              </el-date-picker>
              <span class="u-data-tag">至</span>
              <!-- :picker-options="endPickerOptionsBirthday" -->
              <el-date-picker
                v-model="formData.birthdayEnd"
                type="date"
                size="small"
                value-format="yyyy-MM-dd"
                class="u-item-width-daterange u-data-tag"
                placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="证件号">
              <el-input
                v-model="formData.idNum"
                placeholder="请输入"
                size="small"
                class="u-item-width-normal"
                clearable
              ></el-input>
            </el-form-item>
            <el-form-item label="文化程度">
              <el-select
                v-model="formData.cultureLevel"
                placeholder="请选择"
                size="small"
                class="u-item-width-normal"
                clearable
              >
                <el-option
                  v-for="item in dicts.educationList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label-width="100px" label="岗位类型" prop="postTypes" >
                <el-select v-model="formData.postTypes" multiple collapse-tags clearable size="small" class="u-item-width-normal"> 
                    <el-option
                    v-for="item in dicts.public_welfare_post_type"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                    >
                    </el-option>
                </el-select>
            </el-form-item>
                <el-form-item label="入职时间">
                  <!-- :picker-options="startPickerOptions" -->
              <el-date-picker
                v-model="formData.hireDateFrom"
                type="date"
                size="small"
                class="u-item-width-daterange"
                value-format="yyyy-MM-dd"
                placeholder="开始日期"
              >
              </el-date-picker>
              <span class="u-data-tag">至</span>
                
              <!-- :picker-options="endPickerOptionsBirthday" -->
              <el-date-picker
                v-model="formData.hireDateEnd"
                type="date"
                size="small"
                value-format="yyyy-MM-dd"
                class="u-item-width-daterange u-data-tag"
                placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>
            <el-row type="flex">
              <el-col :span="24" align="right">
                <el-button
                  style="margin-left: 30px"
                  size="small"
                  type="primary "
                  @click="handleSearch"
                  >查询</el-button
                >
                <el-button
                  style="margin-left: 10px"
                  is-plain
                  class="diy-button--white el-button--default"
                  size="small"
                  @click="resetSearch"
                  >重置</el-button
                >
              </el-col>
            </el-row>
          </el-form>
        </div>
  
        <div class="m-table">
          <div class="div_btn">
            <div class="div_btn_left">
              <el-button
                size="small"
                @click="handleAdd"
                type="primary"
                icon="el-icon-plus"
                >新增</el-button
              >
            </div>
            <el-button
              @click="handleExport"
              type="primary"
              size="small"
              class="diy-button--white el-button--default"
              >导出</el-button
            >
            <el-button
              @click="onDeleteBatch"
              style="margin: 0 10px"
              size="small"
              type="primary"
            >
              批量删除
            </el-button>
            <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"
              :before-upload="beforeExcelUpload"
              :http-request="uploadHttpRequest"
            >
              <el-button
                type="primary"
                size="small"
                class="diy-button--white el-button--default"
                :loading="importLoading"
                >导入</el-button
              >
            </el-upload>
            <el-button
              style="margin-left: 10px"
              class="diy-button--blue"
              size="small"
              @click="handleExportModule('room')"
              >下载模板</el-button
            >
          </div>
  
          <el-table
            :data="tableData"
            border
            v-loading="tableLoading"
            class="m-table-item"
            style="width: 100%"
            :height="maxTableHeight"
            @selection-change="onMultiSelection"
          >
            <el-table-column
              type="selection"
              fixed="left"
              align="center"
              width="50"
            />
            <el-table-column
              label="序号"
              fixed="left"
              type="index"
              align="center"
              width="50"
            />
  
            <el-table-column
              prop="name"
              align="center"
              width="100"
              label="姓名"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
  
            <el-table-column
              prop="mobile"
              align="center"
              width="150"
              label="联系电话"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              prop="idNum"
              align="center"
              width="200"
              label="证件号"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              prop="genderName"
              align="center"
              width="80"
              label="性别"
              :show-overflow-tooltip="true"
            >
            <template slot-scope="scope">
            <span>{{ scope.row.gender?scope.row.gender == "1" ? "男":scope.row.gender == "2"?"女" :'--':"--"  }}</span>
            </template>
            </el-table-column>
            <el-table-column
              prop="currentResidence"
              align="center"
              width="100"
              label="居住地址"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              prop="postTypeNames"
              align="center"
              width="100"
              label="岗位类型"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              prop="hireDate"
              align="center"
              width="100"
              label="入职时间"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
            <el-table-column
              prop="remark"
              align="center"
              label="备注"
              :show-overflow-tooltip="true"
            >
            </el-table-column>
           
            <el-table-column
              fixed="right"
              label="操作"
              align="center"
              width="220"
            >
              <template slot-scope="scope">
                <el-button
                  @click="handleDetail(scope.row)"
                  type="text"
                  size="small"
                  >查看</el-button
                >
                <el-button
                  @click="handleEdit(scope.row)"
                  type="text"
                  size="small"
                  >编辑</el-button
                >
  
                <el-button @click="handleDel(scope.row)" type="text" size="small"
                  >删除</el-button
                >
              </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="parseInt(pageSize)"
              layout="sizes, prev, pager, next, total"
              :total="total"
            >
            </el-pagination>
          </div>
        </div>
      </div>
      <el-dialog
        v-if="showAdd"
        :visible.sync="showAdd"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :title="addDiaTitle"
        :modal-append-to-body="false"
        width="720px"
        top="5vh"
        class="dialog-h"
        @closed="showAdd = false"
      >
        <add-form
          ref="ref_add_form"
          @handleComfirm="handleComfirm"
          @handleClose="handleClose"
        ></add-form>
      </el-dialog>
    </div>
  </template>
    
      <script>
  import { requestPost } from "@/js/dai/request";
  import { genderList, binaryOptionList } from "@/js/columns/constants";
  import nextTick from "dai-js/tools/nextTick";
  import { mapGetters } from "vuex";
  import axios from "axios";
  import addForm from "./addForm";
  // import detailForm from "./detailForm";
  //   import editForm from "./editForm";
  
  export default {
    components: { addForm,  },
  
    data() {
      let endDisabledDate = (time) => {
        //这个关键属性我们一定要写在data的里面并且return的外面，这是动态改变区间的关键
        let nowData = Date.now();
        if (this.formData.serviceTimeStart) {
          let serviceTimeStart = new Date(this.formData.serviceTimeStart);
          return (
            time.getTime() < serviceTimeStart - 24 * 60 * 60 * 1000 ||
            time.getTime() === serviceTimeStart - 24 * 60 * 60 * 1000
          );
        } else {
          return time.getTime() > nowData || time.getTime() === nowData;
        }
      };
      // let startDisabledDate = (time) => {
      //   //这个关键属性我们一定要写在data的里面并且return的外面，这是动态改变区间的关键
      //   let nowData = Date.now() - 24 * 60 * 60 * 1000;
      //   return time.getTime() < nowData;
      // };
  
      return {
        tableLoading: false,
        user: {},
        agencyId: "",
        searchH: 170,
        tableData: [],
        genderList,
        binaryOptionList,
        formData: {
            name: "",
            idNum: "",
            gender: "",
            birthdayStart: "",
            birthdayEnd: "",
            cultureLevel: "",
            postType: "",
            hireDateFrom: "",
            hireDateEnd: ""
        },
        pageNo: 1,
        pageSize: window.localStorage.getItem("pageSize") || 20,
        total: 1,
        endPickerOptions: {
          disabledDate: endDisabledDate,
        },
        startPickerOptions: {
          // disabledDate: startDisabledDate
        },
  
        showAdd: false,
        showEdit: false,
        showDetail: false,
        formType: "add",
        addDiaTitle: "新增",
        detailDiaTitle: "详情",
  
        multiSelection: [], // 多选结果
        importLoading: false,
  
        dicts: {
          educationList: [],
          nationList: [],
          public_welfare_post_type:[]
        }, //字典对象
        importCode:[], 
        dataList:[]
      };
    },
    computed: {
      maxTableHeight() {
        const h = this.clientHeight - this.searchH - 330 + this.iframeHeight;
        const _h = this.clientHeight - 330 - this.searchH;
        return this.$store.state.inIframe ? h : _h;
      },
      ...mapGetters(["clientHeight", "iframeHeight"]),
    },
    watch: {},
    async created() {
      await this.getDicts();
    },
    mounted() {
      console.log(this.$store.state);
      this.user = this.$store.state.user;
      this.agencyId = this.user.agencyId;
      this.getTableData();
    },
    methods: {
      // --------------------------------------字典------------------------------------------
      async getDicts() {
        try {
          const requests = [
            this.$http.post("sys/dict/data/nation", {
              formCode: "resi_base_info",
            }),
            this.$http.post("sys/dict/data/education", {
              formCode: "resi_base_info",
            }),
            this.$http.post("sys/dict/data/dictlist", {
              dictType: "public_welfare_post_type",
            }),
          ];
          const dictKeys = ["nationList", "educationList",'public_welfare_post_type']; // 对应的键名
  
          const results = await Promise.all(requests);
          results.forEach((result, index) => {
            if (result.data.code === 0) {
              this.dicts[dictKeys[index]].push(...result.data.data);
            } else {
              console.log(`获取${dictKeys[index]}失败: ${result.data.msg}`);
            }
          });
        } catch (error) {
          console.log("获取字典失败: ", error);
        }
      },
  
      binaryText(value){
         let text = ''
         text = this.binaryOptionList.filter(item=>item.value == value)[0].label
         return text || "--"
      },
      // ------------------------------------事件------------------------------------------
      checkNumberInput(){
          if (isNaN(this.formData.retirementAmount)) {
          this.$message.error('请输入数字');
          this.formData.retirementAmount = '';
          } else {
          this.formData.retirementAmount = parseFloat(this.formData.retirementAmount);
          }
      },
      // 导入
      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.$message({
          showClose: true,
          dangerouslyUseHTMLString: true,
          message:
            "导入中，请到系统管理-<a id='clickA' style='cursor: pointer;'>导入记录</a>中查看进度",
          duration: 3000,
        });
        let than = this;
        document.getElementById("clickA").addEventListener("click", function () {
          than.$router.replace("/main/importRecord-index");
        });
        const formData = new FormData(); //FormData对象，添加参数只能通过append('key', value)的形式添加
        formData.append("file", file.file); //添加文件对象
        formData.append("fileMode",'SUBSISTENCE_ALLOWANCE');
        await this.$http
          .post("/actual/base/importExcelData/extractExcelHead", formData)
          .then((res) => {
            const { metaListData, fileCode, msg } = res.data.data;
            this.dataList = metaListData;
            // 相等于在for循环中写filter过滤,这样写能够以 O(1) 的时间复杂度获取 itemGroupId 匹配的元素。
            this.importCode = fileCode;
            this.handleComfirmUpload()
          })
          .catch((err) => {
            console.log("失败", err);
            file.onError(); //上传失败的文件会从文件列表中删除
            // this.$message.error('导入失败')
          });//
      },
      async handleComfirmUpload () {
          this.importLoading = true;
          this.importBtnTitle = "正在上传中...";
          const { importOption, importCode, dataList } = this;
          const formData = new FormData();
          formData.append("columnMateJson", JSON.stringify(dataList));
          formData.append("fileCode", importCode);
          await this.$http
            .post("/actual/base/importExcelData/importResiHouseExcel", formData)
            .then((res) => {
              console.log("res-up", res);
              if (res.data.code == 0 && res.data.msg == "success") {
                this.getTableData();
              } else this.$message.error(res.data.msg);
            })
            .catch((err) => {
              console.log("失败", err);
              file.onError(); //上传失败的文件会从文件列表中删除
            });
          this.importLoading = false;
          this.importBtnTitle = "导入";
    },
      // 搜索事件
      handleSearch(val) {
        console.log(this.formData);
        this.pageNo = 1;
        this.getTableData();
      },
  
      //   调出新增组件
      async handleAdd() {
        this.addDiaTitle = "新增";
        this.formType = "add";
        this.showAdd = true;
      },
      //   查看详情触发事件
      async handleDetail(row) {
        this.addDiaTitle = "详情";
        this.formType = "detail";
        this.showAdd = true;
        this.$nextTick(() => {
          this.$refs.ref_add_form.initForm("detail", row);
        });
      },
  
      //   编辑触发事件
      async handleEdit(row) {
        this.showAdd = true;
        this.$nextTick(() => {
          this.$refs.ref_add_form.initForm("edit", row);
        });
      },
      //  新增弹出框组件取消事件
      handleClose() {
        this.formType = "";
        this.showAdd = false;
        this.showEdit = false;
      },
      //  新增弹出框组件确定事件
      handleComfirm() {
        this.handleClose();
        this.pageNo = 1;
        this.getTableData();
      },
      //   删除触发事件
      async handleDel(row) {
        this.$confirm("确认删除?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.cancelFuwu([row.categorizedResiId]);
          })
          .catch((err) => {
            if (err == "cancel") {
              // this.$message({
              //   type: "info",
              //   message: "已取消删除"
              // });
            }
          });
      },
      //   删除处理
      async cancelFuwu(id) {
        const url = "/actual/base/resiCategorized/publicWelfarePost/deleteBatch";
        const { data, code, msg } = await requestPost(url, id);
        if (code === 0) {
          this.$message.success("删除成功！");
          this.getTableData();
        } else {
          this.$message.error("操作失败！");
        }
      },
      //   获取列表
      async getTableData() {
        this.tableLoading = true;
        const url = "/actual/base/resiCategorized/publicWelfarePost/page";
  
        const { pageSize, pageNo, formData } = this;
        const { data, code, msg } = await requestPost(url, {
          pageSize,
          pageNo,
          ...formData,
        });
        this.tableLoading = false;
        if (code === 0) {
          this.total = data.total || 0;
          this.tableData = data.list;
        } else {
          this.$message.error(msg);
        }
      },
   
      //   导出
      async handleExport() {
        const url = "/actual/base/resiCategorized/publicWelfarePost/export";
        const { pageSize, pageNo, formData } = this;
        axios({
          url: window.SITE_CONFIG["apiURL"] + url,
          method: "post",
          data: {
            pageSize,
            pageNo,
            ...formData,
          },
          responseType: "blob",
        })
          .then((res) => {
            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.openxmlformats-officedocument.spreadsheetml.sheet",
            });
            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对象
          })
          .catch((err) => {
            console.log("获取导出情失败", err);
            return this.$message.error("网络错误");
          });
      },
      // 下载模板
      async handleExportModule() {
        let url = "/actual/base/resiCategorized/publicWelfarePost/downloadImportTemplate";
        let params = {};
        await this.$http({
          method: "get",
          url,
          responseType: "blob",
          data: params,
        })
          .then((res) => {
            console.log("res----dddd", 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("网络错误");
          });
      },
      //   分页
      handleSizeChange(val) {
        this.pageSize = val;
        window.localStorage.setItem("pageSize", val);
        this.getTableData();
      },
  
      //   分页
      handleCurrentChange(val) {
        this.pageNo = val;
        this.getTableData();
      },
      //   重置
      resetSearch() {
        this.formData = {};
  
        this.pageNo = 1;
        this.getTableData();
      },
      // 多选事件
      onMultiSelection(rows) {
        this.multiSelection = rows;
      },
  
      // 批量删除
      onDeleteBatch() {
        if (this.multiSelection.length == 0) {
          this.$message.warning("请先选中至少一项");
          return;
        }
  
        this.$confirm("删除之后无法恢复，确认删除？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.cancelFuwu(this.multiSelection.map((e) => e.categorizedResiId));
          })
          .catch((err) => {
            console.error(err);
            this.$message.error("删除失败");
          });
      },
    },
  
    props: {},
  };
  </script>
  <style lang="scss" scoped>
  @import "@/assets/scss/buttonstyle.scss";
  @import "@/assets/scss/modules/management/list-main.scss";
  @import "@/assets/scss/modules/shequzhili/event-info.scss";
  .div_btn_left > * {
    margin-right: 10px;
  }
  </style>
    
    