<template>
  <div class="app-container" style="padding-top:0">
    <!-- <div>{{ list }}</div> -->
    <div class="filter-container">
      <!-- <el-button v-if="list" id="te" type="warning" v-has="'editor'">abc</el-button> -->

      <el-input
        v-model="listQuery.params.name"
        style="width:200px;margin-right:10px"
        class="filter-item"
        placeholder="姓名"
        clearable
      />
      <!-- <el-input
        v-model="listQuery.params.nameZ"
        style="width:200px;margin-right:10px"
        class="filter-item"
        placeholder="姓名（藏语）"
        clearable
      /> -->
      <el-input
        v-model="listQuery.params.phone"
        style="width:200px;margin-right:10px"
        class="filter-item"
        placeholder="手机号"
        clearable
      />
      <el-input
        v-model="listQuery.params.idCard"
        style="width:200px;margin-right:10px"
        class="filter-item"
        placeholder="身份证号"
        clearable
      />
      <!-- isConvenience -->

      <!-- <RegionSelect v-model="regionSearchVal" class="filter-item" /> -->
      <el-cascader
        class="filter-item"
        v-model="regionSearchVal"
        style="width:240px"
        :options="regions"
        :props="{ checkStrictly: true }"
        placeholder="行政区域"
        clearable
      />

      <!-- <span style="margin-left:10px;margin-right:10px;"
        >是否是便民工作人员</span
      > -->
      <el-checkbox
        v-model="isStaff"
        @change="handleIsStaff"
        style="margin-left:10px"
        >是否是便民工作人员</el-checkbox
      >
      <!-- <el-switch
        v-model="listQuery.params.isConvenience"
        active-color="#13ce66"
        inactive-color="#ff4949"
      >
      </el-switch> -->

      <el-button type="primary" @click="handleSearch" style="margin-left:10px"
        >搜索</el-button
      >
    </div>
    <el-button
      @click="handleAdd"
      type="primary"
      size="mini"
      style="font-size:12px;padding:10px 20px;margin-bottom:20px"
      >新增</el-button
    >
    <el-button
      :loading="excelUploading"
      v-has="'RESIDENT_IMPORT'"
      @click="handleExcelImport"
      type="primary"
      size="mini"
      style="font-size:12px;padding:10px 20px;margin-bottom:20px"
      >导入</el-button
    >
    <el-table :data="list" style="width: 100%" border v-loading="listLoading">
      <el-table-column prop="name" label="姓名" width="100">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>

      <el-table-column prop="nameZ" label="姓名(藏语)" width="180">
        <template slot-scope="scope">
          {{ scope.row.nameZ }}
        </template>
      </el-table-column>

      <el-table-column prop="phone" label="手机号" width="120">
        <template slot-scope="scope">
          {{ scope.row.phone }}
        </template>
      </el-table-column>

      <el-table-column prop="phone" label="身份证号" width="200">
        <template slot-scope="scope">
          {{ scope.row.idCard }}
        </template>
      </el-table-column>

      <el-table-column prop="phone" label="是否是便民工作人员" width="150">
        <template slot-scope="scope">
          {{ scope.row.isConvenience ? "是" : "否" }}
        </template>
      </el-table-column>

      <el-table-column prop="phone" label="所属行政区域">
        <template slot-scope="scope">
          {{
            scope.row.permanentResidenceRegion +
              (scope.row.permanentResidenceTown
                ? "-" + scope.row.permanentResidenceTown
                : "") +
              (scope.row.permanentResidenceTownShip
                ? "-" + scope.row.permanentResidenceTownShip
                : "")
          }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300px" fixed="right" align="center">
        <template slot-scope="scope">
          <el-button
            @click="handleEdit(scope.row)"
            type="primary"
            size="mini"
            style="font-size:12px;padding:10px 20px"
            >修改</el-button
          >
          <el-button
            @click="handleDelete(scope.row)"
            type="danger"
            size="mini"
            style="font-size:12px;padding:10px 20px;border-radius:21px"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-if="total > 0"
      :total="total"
      :page.sync="listQuery.lastPageIndex"
      :limit.sync="listQuery.size"
      @pagination="getList"
    />

    <el-dialog
      :close-on-click-modal="false"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogAddVisible"
      :close-on-press-escape="false"
      width="60%"
    >
      <el-form
        :model="residentInfo"
        ref="residentInfoForm"
        label-width="155px"
        class="el-form"
        :rules="rules"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="头像">
              <cut-upload
                :fixed-number="[1, 1]"
                :init-url="residentInfo.avatar"
                @imgupload="UploadCbk"
              />
            </el-form-item>

            <el-form-item label="姓名" prop="name">
              <el-input v-model="residentInfo.name" />
            </el-form-item>

            <el-form-item label="姓名（藏文）">
              <el-input v-model="residentInfo.nameZ" />
            </el-form-item>

            <el-form-item label="性别">
              <el-radio v-model="residentInfo.sex" :label="0">女</el-radio>
              <el-radio v-model="residentInfo.sex" :label="1">男</el-radio>
              <el-radio v-model="residentInfo.sex" :label="2">未知</el-radio>
            </el-form-item>

            <el-form-item label="手机号">
              <el-input v-model="residentInfo.phone" />
            </el-form-item>

            <el-form-item label="身份证号" prop="idCard">
              <el-input v-model="residentInfo.idCard" />
            </el-form-item>

            <el-form-item label="身份证地址">
              <el-input v-model="residentInfo.idCardAddress" />
            </el-form-item>
          </el-col>
          <el-col :span="12" style="padding-top:40px">
            <el-form-item label="职务">
              <el-input v-model="residentInfo.duty" />
            </el-form-item>

            <el-form-item label="职务（藏文）">
              <el-input v-model="residentInfo.dutyZ" />
            </el-form-item>

            <el-form-item label="职责">
              <el-input v-model="residentInfo.description" />
            </el-form-item>

            <el-form-item label="职责（藏文）">
              <el-input v-model="residentInfo.descriptionZ" />
            </el-form-item>

            <el-form-item label="序号">
              <el-input v-model="residentInfo.sort" />
            </el-form-item>

            <el-form-item label="所属">
              <el-select v-model="residentInfo.organizationAttribution" clearable placeholder="所属">
                <el-option
                  v-for="item in organizationAttributionList"
                  :key="item"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="行政区域" prop="regionIds">
              <el-cascader
                v-model="residentInfo.regionIds"
                style="width:240px"
                :options="regions"
                :props="{ checkStrictly: true }"
                placeholder="行政区域"
                clearable
              />
            </el-form-item>

            <el-form-item label="是否是便民工作人员">
              <el-switch v-model="residentInfo.isConvenience"></el-switch>
            </el-form-item>

            <el-form-item label="是否是便民领导">
              <el-switch v-model="residentInfo.isConvenienceLeader"></el-switch>
            </el-form-item>

            <el-form-item label="授权权限" v-has="'RESIDENT_SET_ADMIN'">
              <el-select
                v-model="residentInfo.isResidentsAdministrator"
                multiple
              >
                <el-option
                  label="设置权限"
                  value="RESIDENT_SET_ADMIN"
                ></el-option>
                <el-option label="居民管理" value="RESIDENT_ADMIN"></el-option>
                <el-option label="地区领导" value="WORKORDER_ADMIN"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- <el-form-item label="是否是融媒体工作人员">
          <el-switch v-model="residentInfo.isNews"></el-switch>
        </el-form-item>

        <el-form-item label="是否是融媒体领导">
          <el-switch v-model="residentInfo.isNewsLeader"></el-switch>
        </el-form-item> -->
      </el-form>

      <!-- logconven.ne -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogAddVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      title="提示"
      :visible.sync="dialogDeleteConfirm"
      width="30%"
      center
    >
      <span>确定删除吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogDeleteConfirm = false">取 消</el-button>
        <el-button type="primary" @click="deleteData">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog title="提示" :visible.sync="dialogExcelImport" width="30%">
      <ReadExcel @listenToChildEvent="getExcelData" ref="readExcel"></ReadExcel>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogExcelImport = false">取 消</el-button>
        <el-button type="primary" @click="dialogExcelImport = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getResidentInfoList,
  addResidentInfoList,
  updateResidentInfo,
  deleteResident,
  residentInfo
} from "@/api/residentInformation";
import RegionSelect from "@/components/RegionSelect";
import { getRegions } from "@/api/region";
import Pagination from "@/components/Pagination";
import CutUpload from "@/components/cutUploadImage/index.vue";
import ReadExcel from "@/components/ReadExcel/index";

export default {
  components: { Pagination, CutUpload, RegionSelect, ReadExcel },
  data() {
    return {
      listLoading: false,
      total: 0,
      listQuery: {
        lastPageIndex: 1,
        size: 10,
        params: {
          name: "",
          phone: "",
          idCard: ""
        }
      },
      dialogAddVisible: false,
      textMap: {
        update: "修改",
        create: "创建"
      },
      dialogStatus: "",
      list: [],
      regions: [],
      organizationAttributionList: ["卫生院", "派出所"],
      rules: {
        name: [
          { required: true, message: "居民姓名不能为空", trigger: "blur" }
        ],
        idCard: [
          { required: true, message: "居民身份证号不能为空", trigger: "blur" }
        ],
        regionIds: [
          { required: true, message: "行政区域不能为空", trigger: "blur" }
        ]
      },
      residentInfo: {
        avatar: ""
      },
      regionSearchVal: undefined,
      dialogDeleteConfirm: false,
      isStaff: false,
      excelUploading: false,
      dialogExcelImport: false
    };
  },
  created() {
    this.getList();
    this.getRegions();
  },
  methods: {
    getList() {
      this.listLoading = true;
      getResidentInfoList(this.listQuery).then(res => {
        this.list = res.d.list;
        this.total = res.d.total;
        this.listLoading = false;
      });
    },
    getRegions() {
      getRegions().then(res => {
        const tempData = res.d;
        const countyArr = []; // 县,1
        tempData.map(county => {
          const countyObj = {
            value: county.root.name,
            label: county.root.name,
            disabled: !county.root.check,
            children: []
          };
          countyArr.push(countyObj);
          county.node.map(town => {
            const townObj = {
              value: town.root.name,
              label: town.root.name,
              disabled: !town.root.check,
              children: []
            };
            countyObj.children.push(townObj);
            town.node.map(country => {
              townObj.children.push({
                value: country.root.name,
                label: country.root.name,
                disabled: !country.root.check
              });
            });
          });
        });
        this.regions = countyArr;
      });
    },
    handleSearch() {
      this.listQuery.params.isConvenience = this.isStaff ? true : undefined;
      if (this.regionSearchVal) {
        switch (this.regionSearchVal.length) {
          case 1:
            this.listQuery.params.PermanentResidenceRegion = this.regionSearchVal[0];
            this.listQuery.params.PermanentResidenceTown = undefined;
            this.listQuery.params.PermanentResidenceTownShip = undefined;
            break;
          case 2:
            this.listQuery.params.PermanentResidenceTown = this.regionSearchVal[1];
            this.listQuery.params.PermanentResidenceRegion = undefined;
            this.listQuery.params.PermanentResidenceTownShip = undefined;
            break;
          case 3:
            this.listQuery.params.PermanentResidenceTownShip = this.regionSearchVal[2];
            this.listQuery.params.PermanentResidenceRegion = undefined;
            this.listQuery.params.PermanentResidenceTown = undefined;
            break;
          default:
            this.listQuery.params.PermanentResidenceRegion = undefined;
            this.listQuery.params.PermanentResidenceTown = undefined;
            this.listQuery.params.PermanentResidenceTownShip = undefined;
            break;
        }
        // this.listQuery.params.permanentResidenceRegion = this.regionSearchVal[0];
        // this.listQuery.params.permanentResidenceTown = this.regionSearchVal[1];
        // this.listQuery.params.permanentResidenceTownShip = this.regionSearchVal[2];
      }
      this.getList();
    },
    resetResidentInfo() {
      this.residentInfo = {
        id: undefined,
        avatar: undefined,
        name: undefined,
        nameZ: undefined,
        description: undefined,
        descriptionZ: undefined,
        duty: undefined,
        dutyZ: undefined,
        idCard: undefined,
        idCardAddress: undefined,
        isConvenience: false,
        isConvenienceLeader: false,
        isNews: false,
        isNewsLeader: false,
        isResidentsAdministrator: [],
        phone: undefined,
        sex: undefined,
        regionIds: undefined,
        sort: undefined
      };
    },
    UploadCbk(data) {
      this.residentInfo.avatar = data;
    },
    handleAdd() {
      this.resetResidentInfo();

      this.dialogStatus = "create";
      this.$nextTick(() => {
        this.dialogAddVisible = true;
      });
    },
    formatSubmitParams() {
      let regions = this.residentInfo.regionIds;
      this.residentInfo.permanentResidenceRegion = regions[0];
      this.residentInfo.permanentResidenceTown = regions[1];
      this.residentInfo.permanentResidenceTownShip = regions[2];
    },
    createData() {
      this.$refs.residentInfoForm.validate(valid => {
        if (valid) {
          this.formatSubmitParams();
          let payload = [];
          let info = Object.assign({}, this.residentInfo);
          delete info.regionIds;
          payload.push(info);

          addResidentInfoList(payload).then(res => {
            if (res.c === 200) {
              this.$notify.success("创建成功");
              this.dialogAddVisible = false;
              this.getList();
            } else {
              this.$notify.error(res.m);
            }
          });
        }
      });
    },
    updateData() {
      this.$refs.residentInfoForm.validate(valid => {
        if (valid) {
          this.formatSubmitParams();
          delete this.residentInfo.regionIds;
          updateResidentInfo(this.residentInfo).then(res => {
            // console.log(res);
            if (res.c === 200) {
              this.$notify.success("修改成功");
              this.dialogAddVisible = false;
              this.getList();
            } else {
              this.$notify.error(res.m);
            }
          });
        }
      });
    },
    handleEdit(row) {
      residentInfo({ id: row.id }).then(res => {
        // console.log(res);
        this.residentInfo = Object.assign({}, res.d);
        let arr = [];
        if (this.residentInfo.permanentResidenceRegion) {
          arr.push(this.residentInfo.permanentResidenceRegion);
        }
        if (this.residentInfo.permanentResidenceTown) {
          arr.push(this.residentInfo.permanentResidenceTown);
        }
        if (this.residentInfo.permanentResidenceTownShip) {
          arr.push(this.residentInfo.permanentResidenceTownShip);
        }
        this.residentInfo.regionIds = arr;

        this.dialogStatus = "update";
        this.dialogAddVisible = true;
      });
    },
    handleDelete(row) {
      this.residentInfo = Object.assign({}, row);
      this.dialogDeleteConfirm = true;
    },
    deleteData() {
      deleteResident({ id: this.residentInfo.id }).then(res => {
        // console.log(res);
        if (res.c === 200) {
          this.$notify.success("删除成功");
          this.dialogDeleteConfirm = false;
          this.getList();
        } else {
          this.$notify.error(res.m);
        }
      });
    },
    handleIsStaff(val) {
      // console.log(val);
      if (val === false) {
        // console.log('ab');
        this.listQuery.params.isConvenience === undefined;
        let temp = Object.assign({}, this.listQuery);
        temp.params.isConvenience === undefined;
        this.listQuery = temp;
        // console.log(this.listQuery);
      }
      // if (!val) {
      //   this.listQuery.params.isConvenience === undefined;
      //   console.log(this.listQuery.params);
      // }
    },
    handleExcelImport() {
      this.dialogExcelImport = true;
    },
    getExcelData(data) {
      this.excelUploading = true;
      addResidentInfoList(data)
        .then(res => {
          if (res.c === 200) {
            this.$notify.success("导入成功");
            setTimeout(() => {
              this.excelUploading = false;
            }, 3000);
            this.dialogExcelImport = false;
            this.getList();
          } else {
            this.$notify.error(res.m);
            setTimeout(() => {
              this.excelUploading = false;
            }, 3000);
            this.dialogExcelImport = false;
          }
        })
        .catch(error => {
          this.$notify.error(error);
        });
    }
  }
};
</script>

<style></style>
