<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-input
              v-model="formData.mobile"
              placeholder="请输入"
              size="small"
              class="u-item-width-normal"
              clearable
            ></el-input>
          </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.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-select
              v-model="formData.localResidenceFlag"
              placeholder="请输入"
              size="small"
              class="u-item-width-normal"
              clearable
            >
              <el-option
                v-for="item in binaryOptionList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="居住地址">
            <el-input
              v-model="formData.currentResidence"
              placeholder="请输入"
              size="small"
              class="u-item-width-normal"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="残疾类别">
            <el-select
              v-model="formData.disabilityCategoryCode"
              placeholder="请选择"
              size="small"
              class="u-item-width-normal"
              clearable
            >
              <el-option
                v-for="item in dicts.disability_category_code"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="残疾级别">
            <el-select
              v-model="formData.disabilityLevel"
              placeholder="请选择"
              size="small"
              class="u-item-width-normal"
              clearable
            >
              <el-option
                v-for="item in dicts.disability_level"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="残疾证号">
            <el-input
              v-model="formData.disabilityNum"
              placeholder="请输入"
              size="small"
              class="u-item-width-normal"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="低保">
            <el-select
              v-model="formData.subsistenceAllowanceFlag"
              placeholder="请选择"
              size="small"
              class="u-item-width-normal"
              clearable
            >
              <el-option
                v-for="item in binaryOptionList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="月收入">
            <el-input
              v-model="formData.monthIncome"
              placeholder="请输入"
              size="small"
              class="u-item-width-normal"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="联系人">
            <el-input
              v-model="formData.contactName"
              placeholder="请输入"
              size="small"
              class="u-item-width-normal"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input
              v-model="formData.contactMobile"
              placeholder="请输入"
              size="small"
              class="u-item-width-normal"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="formData.remark"
              placeholder="请输入"
              size="small"
              class="u-item-width-normal"
              clearable
            ></el-input>
          </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>
          <!-- 
              :on-success="handleExcelSuccess"
            :before-upload="beforeExcelUpload"
            :http-request="uploadHttpRequest"
         -->
          <el-upload
            :headers="$getElUploadHeaders()"
            ref="upload"
            class="upload-demo"
            action="uploadUlr"
            :limit="1"
            :accept="'.xls,.xlsx'"
            :with-credentials="true"
            :show-file-list="false"
            :auto-upload="true"
          >
            <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="200"
            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="localResidenceFlag"
            align="center"
            width="100"
            label="本地户籍"
            :show-overflow-tooltip="true"
          >
          <template slot-scope="scope">
              <span>{{binaryText(scope.row.localResidenceFlag)}}</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="disabilityCategoryName"
            align="center"
            width="100"
            label="残疾类别"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            prop="disabilityLevelName"
            align="center"
            width="80"
            label="残疾级别"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            prop="disabilityNum"
            align="center"
            width="200"
            label="残疾证号"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            prop="subsistenceAllowanceFlag"
            align="center"
            width="80"
            label="低保"
            :show-overflow-tooltip="true"
          >
          <template slot-scope="scope">
              <span>{{binaryText(scope.row.subsistenceAllowanceFlag)}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="contactName"
            align="center"
            width="80"
            label="联系人"
            :show-overflow-tooltip="true"
          >
          </el-table-column>

          <el-table-column
            prop="contactMobile"
            align="center"
            width="200"
            label="联系电话"
            :show-overflow-tooltip="true"
          >
          </el-table-column>

          <el-table-column
            prop="remark"
            align="center"
            width="100"
            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
              >
              <!--       v-if="scope.row.serviceStatus === 'in_service'" -->
              <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"
        :formType="formType"
        @handleComfirm="handleComfirm"
        @handleClose="handleClose"
      ></add-form>
    </el-dialog>
    <!-- <el-dialog
      v-if="showDetail"
      :visible.sync="showDetail"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :title="detailDiaTitle"
      :modal-append-to-body="false"
      width="850px"
      top="5vh"
      class="dialog-h"
      @closed="diaDetailClose"
    >
      <detail-form
        ref="ref_detail_form"
        @diaDetailClose="diaDetailClose"
      >
      </detail-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";

export default {
  //   detailForm
  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: "",
        mobile: "",
        gender: "",
        idNum: "",
        localResidenceFlag: null,
        currentResidence: "",
        disabilityCategoryCode: "",
        disabilityLevel: "",
        disabilityNum: "",
        subsistenceAllowanceFlag: null,
        monthIncome: null,
        contactName: "",
        contactMobile: null,
        remark: "",
      },
      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: {
        disability_category_code: [],
        disability_level: [],
      }, //字典对象
    };
  },
  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 dictTypes = ["disability_category_code", "disability_level"]; // 把所有dictType放在这个数组里
        const requests = dictTypes.map((dictType) => {
          return this.$http.post("sys/dict/data/dictlist", {
            dictType: dictType,
          });
        });
        const results = await Promise.all(requests);
        results.forEach((result, index) => {
          if (result.data.code === 0) {
            this.dicts[dictTypes[index]].push(...result.data.data);
          } else {
            console.log(`获取${dictTypes[index]}字典失败: ${result.msg}`);
          }
        });
      } catch (error) {
        console.log("获取字典失败: ", error);
      }
    },
    binaryText(value){
       let text = ''
       text = this.binaryOptionList.filter(item=>item.value == value)[0].label
       return text || "--"
    },
    // ------------------------------------事件------------------------------------------
    // 搜索事件
    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);
      });
    },
    //   详情弹出框取消事件
    diaDetailClose() {
      this.$refs.ref_detail_form.diaDestroy();
      this.showDetail = false;
    },
    //   编辑触发事件
    async handleEdit(row) {
      this.addDiaTitle = "编辑";
      this.formType = "edit";
      this.showAdd = true;
      this.$nextTick(() => {
        this.$refs.ref_add_form.initForm("edit", row);
      });
    },
    //  新增弹出框组件取消事件
    handleClose() {
      this.formType = "";
      this.showAdd = false;
      this.showDetail = 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/disability/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/disability/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 = "";
      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/disability/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>
  