<template>
  <div class="g-main">
    <div>
      <div class="m-search">
        <el-form
          :inline="true"
          :model="formData"
          ref="ref_searchform"
          :label-width="'105px'"
        >
          <el-form-item label="名称模糊查询">
            <el-select
              v-model="basicType"
              class="u-item-width-service"
              clearable
              size="small"
            >
              <template>
                <el-option
                  @click.native="handelClickBasicType"
                  :label="item.label"
                  :value="item.value"
                  v-for="(item, index) in basicInfoList"
                  :key="index"
                >
                </el-option>
              </template>
            </el-select>
          </el-form-item>
          <el-form-item
            v-for="(item, index) in basicInfoList"
            :key="index"
            v-if="basicType == item.value"
          >
            <el-input
              v-model="formData[item.value]"
              class="u-item-width-service"
              placeholder="请输入"
              clearable
              size="small"
            >
            </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-input
              v-model="formData.ageFrom"
              @change="handleAgeChange"
              class="u-item-width-daterange"
              placeholder="请输入"
              clearable
              size="small"
            >
            </el-input>
            <span class="u-data-tag">至</span>
            <el-input
              v-model="formData.ageTo"
              @change="handleAgeChange"
              class="u-item-width-daterange u-data-tag"
              placeholder="请输入"
              clearable
              size="small"
            >
            </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> -->
        </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
            prop="resiName"
            align="center"
            width="100"
            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="age"
            align="center"
            width="50"
            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="homeFullName"
            align="center"
            width="100"
            label="居住房屋"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            prop="resiCategoriesStr"
            align="center"
            label="居民分类"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            prop="partyFlag"
            align="center"
            width="100"
            label="政治面貌"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              {{
                scope.row.gender
                  ? scope.row.partyFlag === 1
                    ? "党员"
                    : scope.row.partyFlag === 2
                    ? "共青团员"
                    : scope.row.partyFlag === 0
                    ? "群众"
                    : "--"
                  : "--"
              }}
            </template>
          </el-table-column>
          <el-table-column
            prop="synthesizeScore"
            align="center"
            width="100"
            label="完整度得分"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            prop="updateTime"
            align="center"
            width="100"
            label="最近更新时间"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            align="center"
            width="120"
          >
            <template slot-scope="scope">
              <el-button
                @click="handleLook(scope.row)"
                type="text"
                size="small"
                >查看</el-button
              >
              <el-button @click="handleEdit(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 title="密码验证" :visible.sync="showCheckPassword">
      <el-form
        :model="checkPasswordFrom"
        :rules="checkPasswordRulse"
        ref="checkPasswordFrom"
      >
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="checkPasswordFrom.password"
            autocomplete="off"
            type="password"
            placeholder="请输入当前账号密码"
            @keydown.native.enter="handelClickCheckPassword"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showCheckPassword = false">取 消</el-button>
        <el-button type="primary" @click="handelClickCheckPassword"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
    
      <script>
import { requestPost, requestGet } from "@/js/dai/request";
import nextTick from "dai-js/tools/nextTick";
import { genderList } from "@/js/columns/constants";
import { mapGetters } from "vuex";
import axios from "axios";
export default {
  components: {},

  data() {
    return {
      tableLoading: false,
      user: {},
      agencyId: "",
      searchH: 170,
      tableData: [],
      genderList,
      editUserId: "",
      showCheckPassword:false,
      formData: {
        ageFrom: "",
        ageTo: "",
        resiName: "",
        mobile: "",
        idNum: "",
        nativePlace: "",
        gender: "",
      },
      pageNo: 1,
      pageSize: window.localStorage.getItem("pageSize") || 20,
      checkPasswordFrom: {
        password: "",
      },
      checkPasswordRulse: {
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 18,
            message: "长度在 6 到 18 个字符",
            trigger: "blur",
          },
        ],
      },
      total: 0,
      
      basicType: "resiName",
      basicInfoList: [
        {
          label: "姓名",
          value: "resiName",
        },
        {
          label: "联系电话",
          value: "mobile",
        },
        {
          label: "证件号",
          value: "idNum",
        },
      ],
    };
  },
  computed: {
    maxTableHeight() {
      const h = this.clientHeight - this.searchH - 330 + this.iframeHeight;
      const _h = this.clientHeight - 250 - this.searchH;
      return this.$store.state.inIframe ? h : _h;
    },
    ...mapGetters(["clientHeight", "iframeHeight"]),
  },
  watch: {
    "$route.query"(newVal, oldVal) {
      this.getTableData();
    },
  },
  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",
          }),
        ];
        const dictKeys = ["nationList", "educationList"]; // 对应的键名

        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);
      }
    },
    // ------------------------------------事件------------------------------------------
    handelClickBasicType() {
      this.formData.name = "";
      this.formData.mobile = "";
      this.formData.idNum = "";
      this.formData.nativePlace = "";
      this.formData.remark = "";
    },
    handleAgeChange() {
      if (this.formData.ageStart && this.formData.ageEnd) {
        if (this.formData.ageStart > this.formData.ageEnd) {
          this.$message.warning("结束年龄不能小于开始年龄");
        }
      }
    },
    // 搜索事件
    handleSearch(val) {
      console.log(this.formData);
      this.pageNo = 1;
      this.getTableData();
    },

    async handleAdd() {
      this.$router.push({ name: "add-resi" });
    },
    //   查看详情触发事件
    async handleLook(row) {
      this.lookResiId = row.resiId;
      let {
        agencyId,
        gridId,
        gridName,
        gender,
        homeId,
        homeName,
        resiName,
        resiId,
      } = row;
      this.$store.dispatch("saveData", {
        agencyId,
        gridId,
        gridName,
        gender,
        homeId,
        homeName,
        name:resiName,
        resiId,
      });
      this.$router.push({ name: "jumin-huaxiang" });
      this.$store.state.contentTabs = this.$store.state.contentTabs.map(
        (item) => {
          if (item.name === "jumin-huaxiang") {
            return { ...item, title: name };
          }
          return item;
        }
      );
    },
    //   编辑触发事件
    async handleEdit(row) {
      this.editUserId = row.resiId;
      this.showCheckPassword = true;
    },
  
    //   获取列表
    async getTableData() {
      this.tableLoading = true;
      const url =
        "/actual/base/residentIntegrity/resiCategoryStats/nonIntResiList";
        const query = this.$route.query;
      this.houseId = query.houseId;
      const { pageSize, pageNo, formData } = this;
      const { data, code, msg } = await requestGet(url, {
        pageSize,
        pageNo,
        resultScopeType: this.$route.query.type || null,
        resiCategory: this.$route.query.resiCategory || null, //首页传参进来
        ...formData,
      });
      data.list.forEach((item) => {
          if (item.resiCategories) {
            item.resiCategoriesStr = item.resiCategories
              .map((item) => item.categoryName)
              .join(",");
          }
      });
      this.tableLoading = false;
      if (code === 0) {
        this.total = data.total || 0;
        this.tableData = data.list;
      } else {
        this.$message.error(msg);
      }
    },
    // 密码验证
    handelClickCheckPassword() {
      this.$refs.checkPasswordFrom.validate(async (vali) => {
        if (vali) {
          const url = `/actual/base/residentBaseInfo/getResiUserInfo/${this.editUserId}`;
          let parm = {
            password: this.checkPasswordFrom.password,
          };
          const { data, code, msg } = await requestPost(url, parm);
          if (code === 0) {
            this.showCheckPassword = false;
            this.$router.push({
              name: "edit-resi",
              query: { id: this.editUserId },
              params: { idNum: data.idNum, mobile: data.mobile,name:data.name },
            });
            this.checkPasswordFrom.password = "";
          } else {
            this.$message.error(msg);
          }
        } else {
          return false;
        }
      });
    },
    //   分页
    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>
    
    