<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.basicinfo_delete"
                   @click="handleDelete">删 除
        </el-button>
        <el-button type="warning"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.basicinfo_delete"
                   @click="handleDelFace">人脸删除
        </el-button>
      </template>
      <template slot="residentialIdForm" slot-scope="scope">
        <select-dialog-residential :name="form.residentialName" :id="form.residentialId" :disabled="residentialDisabled" :callback="selectCallback"></select-dialog-residential>
      </template>
      <!--      <template slot="buildingId" slot-scope="scope">
              <span v-if="scope.row.buildingId!==-1">
                {{scope.row.buildingName}}
              </span>
            </template>
            <template slot="floorId" slot-scope="scope">
              <span v-if="scope.row.floorId!==-1">
                {{scope.row.floorName}}
              </span>
            </template>
            <template slot="unitId" slot-scope="scope">
              <span v-if="scope.row.unitId!==-1">
                {{scope.row.unitName}}
              </span>
            </template>
            <template slot="roomId" slot-scope="scope">
              <span v-if="scope.row.roomId!==-1">
                {{scope.row.roomName}}
              </span>
            </template>

            <template slot="menu" slot-scope="scope">
              <el-button icon="el-icon-setting" size="mini" type="text">
                <el-dropdown>
                  <span class="el-dropdown-link" style="font-size: xx-small; color: #4babfe">设置标签<i class="el-icon-arrow-down el-icon&#45;&#45;right"></i></span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item type="text" @click.native="tagsFormOpen('elder', scope.row)">高龄老人</el-dropdown-item>
                    <el-dropdown-item type="text" @click.native="tagsFormOpen('keyPerson', scope.row)">重点人员</el-dropdown-item>
                    <el-dropdown-item type="text" @click.native="tagsFormOpen('disabler', scope.row)">残障人士</el-dropdown-item>
                    &lt;!&ndash;              <el-dropdown-item type="text" @click.native="tagsFormOpen('household', scope.row)">常住人员</el-dropdown-item>&ndash;&gt;
                    &lt;!&ndash;              <el-dropdown-item type="text" @click.native="tagsFormOpen('enterpriseStaff', scope.row)">企业员工</el-dropdown-item>&ndash;&gt;
                  </el-dropdown-menu>
                </el-dropdown>
              </el-button>
            </template>
            标签点击事件
            <template slot="tags" slot-scope="scope" style="display: flex">
              <div v-if="scope.row.tags!== null">
              <el-button style="margin: auto" class="el-icon-collection-tag" v-for="item in scope.row.tags.split('，')" @click.native="tagsDetail(item,scope.row)" size="mini" type="text">
                {{item}}
              </el-button>
              </div>
            </template>-->
    </avue-crud>
   <!--     显示标签详情组件
        <el-dialog title="残障人士【标签详情】" :visible.sync="disablerTagsdetail" :modal-append-to-body="false">
          <DisablerTagsDetail v-if="disablerTagsdetail" :basic-data="basicData"></DisablerTagsDetail>
        </el-dialog>
        <el-dialog title="高龄老人【标签详情】" :visible.sync="elderTagsdetail" :modal-append-to-body="false">
          <ElderTagsDetail v-if="elderTagsdetail" :basic-data="basicData"></ElderTagsDetail>
        </el-dialog>
        <el-dialog title="重点人员【标签详情】" :visible.sync="keyPersonTagsdetail" :modal-append-to-body="false">
          <KeypeopleTagsDetail v-if="keyPersonTagsdetail" :basic-data="basicData"></KeypeopleTagsDetail>
        </el-dialog>
        <el-dialog title="常住人员【标签详情】" :visible.sync="householdTagsdetail" :modal-append-to-body="false">
          <HouseholdTagsDetail v-if="householdTagsdetail" :basic-data="basicData"></HouseholdTagsDetail>
        </el-dialog>
        <el-dialog title="企业员工【标签详情】" :visible.sync="enterpriseStaffTagsdetail" :modal-append-to-body="false">
          <EnterpriseStaffTagsDetail v-if="enterpriseStaffTagsdetail" :basic-data="basicData"></EnterpriseStaffTagsDetail>
        </el-dialog>
        标签添加信息组件
        <el-dialog title="高龄老人【添加标签信息】" :visible.sync="elderTags" :modal-append-to-body="false">
          <ElderTagsForm v-if="elderTags" :basic-data="basicData" :close-fn="() => {elderTags = false}"></ElderTagsForm>
        </el-dialog>
        <el-dialog title="残障人士【添加标签信息】" :visible.sync="disablerTags" :modal-append-to-body="false">
          <DisablerTagsForm v-if="disablerTags" :basic-data="basicData" :close-fn="() => {disablerTags = false}"></DisablerTagsForm>
        </el-dialog>
        <el-dialog title="重点人员【添加标签信息】" :visible.sync="keyPersonTags" :modal-append-to-body="false">
          <KeyPersonTagsForm v-if="keyPersonTags" :basic-data="basicData" :close-fn="() => {keyPersonTags = false}"></KeyPersonTagsForm>
        </el-dialog>
        <el-dialog title="常住人员【添加标签信息】" :visible.sync="householdTags" :modal-append-to-body="false">
          <HouseholdTagsForm v-if="householdTags" :basic-data="basicData" :close-fn="() => {householdTags = false}"></HouseholdTagsForm>
        </el-dialog>
        <el-dialog title="企业人员【添加标签信息】" :visible.sync="enterpriseStaffTags" :modal-append-to-body="false">
          <EnterpriseStaffTagsForm v-if="enterpriseStaffTags" :basic-data="basicData" :close-fn="() => {enterpriseStaffTags = false}"></EnterpriseStaffTagsForm>
        </el-dialog>-->
  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/person/basicinfo";
  import {mapGetters} from "vuex";
  /*import ElderTagsForm from "@/components/person-tags/elderTags-form";
  import DisablerTagsForm from "@/components/person-tags/disablerTags-form";
  import KeyPersonTagsForm from "@/components/person-tags/keyPersonTags-form";
  import EnterpriseStaffTagsForm from "@/components/person-tags/enterpriseStaffTags-form";
  import HouseholdTagsForm from "@/components/person-tags/householdTags-form";
  import ElderTagsDetail from "@/components/person-tags/elderTags-detail";
  import DisablerTagsDetail from "@/components/person-tags/disablerTags-detail";
  import KeypeopleTagsDetail from "@/components/person-tags/keyPersonTags-detail";
  import HouseholdTagsDetail from "@/components/person-tags/householdTags-detail";
  import EnterpriseStaffTagsDetail from "@/components/person-tags/enterpriseStaffTags-detail";*/
  import {DIC} from "@/api/util/nation"
  import {validatePhone} from "../../util/validator";
  import SelectDialogResidential from "../../components/select-dialog/select-dialog-residential";

  export default {
    components: {SelectDialogResidential},
    // components: {ElderTagsForm, DisablerTagsForm,KeyPersonTagsForm,DisablerTagsDetail,ElderTagsDetail,KeypeopleTagsDetail},
    data() {
      return {
        elderTags: false,
        disablerTags: false,
        keyPersonTags: false,
        householdTags:false,
        enterpriseStaffTags:false,
        elderTagsdetail:false,
        disablerTagsdetail:false,
        keyPersonTagsdetail:false,
        // householdTagsdetail:false,
        // enterpriseStaffTagsdetail:false,
        basicData: {},
        form: {},
        oldForm: {},
        delTags:[],
        confirmInfo:'',
        query: {},
        loading: true,
        residentialDisabled: false,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option: {
          // excelBtn:true,
          height:'auto',
          calcHeight: 30,
          labelWidth: 120,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          // menuWidth:500,
          column: [
            {
              label: "身份证号",
              labelWidth: 150,
              prop: "idCard",
              search:true,
              hide: true,
              rules: [{
                required: false,
                message: "请输入身份证号码",
                trigger: "blur"
              }]
            },
            {
              label: "姓名",
              prop: "name",
              search:true,
              rules: [{
                required: true,
                message: "请输入姓名",
                trigger: "blur"
              }]
            },
            {
              label: "性别",
              prop: "sex",
              type: 'select',
              dataType:"number",
              search:true,
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=sex",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: true,
                message: "请选择性别",
                trigger: "blur"
              }]
            },
            {
              label: "照片",
              prop: "imageUri",
              type: 'upload',
              hide:true,
              listType: 'picture-img',
              propsHttp: {
                res: "data",
                url: "link"
              },
              action: "/api/blade-resource/oss/endpoint/put-file",
              tip: '只能生产jpg/png图片，且不超过500kb',
              rules: [{
                required: false,
                message: "请上传入境证明url",
                trigger: "blur"
              }]
            },
            /*{
              label: "所属社区",
              prop: "agencyId",
              search: true,
              cascaderItem: ['residentialId'],
              type: "select",
              // remote: true,
              dicUrl: "/api/cyzh-community/agency/list?size=500",
              dicFormatter:(res)=>{
                return res.data.records;//返回字典的层级结构
              },
              props: {
                label: "name",
                value: "id"
              },
              rules: [{
                required: true,
                message: "请选择所属社区",
                trigger: "blur"
              }]
            },*/
            {
              label: "所属小区",
              prop: "residentialId",
              type: "select",
              search: true,
              searchFilterable: true,
              // cascaderItem: ['buildingId'],
              dicUrl: "/api/cyzh-community/residential/list",
              dicFormatter:(res)=>{
                return res.data.records;//返回字典的层级结构
              },
              // dicFlag: false,
              filterable: true,
              formslot: true,
              props: {
                label: "name",
                value: "id"
              },
              rules: [{
                required: true,
                message: "请选择所属小区",
                trigger: "blur"
              }],
              hide: true,
              viewDisplay: false
            },
            {
              label: "所属楼栋",
              prop: "buildingName",
              addDisplay: false,
              editDisplay: false,
            },
            {
              label: "所属楼栋",
              prop: "buildingId",
              type: "select",
              // slot:true,
              search: true,
              cascaderItem: ['unitId'],
              // dicUrl: "/api/cyzh-community/building/list?residentialId={{key}}&size=100",
              dicUrl: "/api/cyzh-community/building/list",
              dicFormatter:(res)=>{
                return res.data.records;//返回字典的层级结构
              },
              // dicFlag: true,
              // filterable: true,
              props: {
                label: "name",
                value: "id"
              },
              rules: [{
                required: true,
                message: "请选择楼栋",
                trigger: "blur"
              }],
              hide: true,
              viewDisplay: false
            },
            {
              label: "所属单元",
              prop: "unitName",
              addDisplay: false,
              editDisplay: false,
            },
            {
              label: "所属单元",
              prop: "unitId",
              type: "select",
              // slot:true,
              search: true,
              cascaderItem: ['floorId'],
              dicUrl: "/api/cyzh-community/unit/list?buildingId={{key}}&size=500",
              dicFormatter:(res)=>{
                return res.data.records;//返回字典的层级结构
              },
              // dicFlag: false,
              // filterable: true,
              props: {
                label: "name",
                value: "id"
              },
              rules: [{
                required: true,
                message: "请选择单元",
                trigger: "blur"
              }],
              hide: true,
              viewDisplay: false
            },
            {
              label: "所属楼层",
              prop: "floorName",
              addDisplay: false,
              editDisplay: false,
            },
            {
              label: "所属楼层",
              prop: "floorId",
              type: "select",
              // slot:true,
              search: true,
              cascaderItem: ['roomId'],
              dicUrl: "/api/cyzh-community/floor/list?unitId={{key}}&size=100",
              dicFormatter:(res)=>{
                return res.data.records;//返回字典的层级结构
              },
              // dicFlag: false,
              filterable: true,
              props: {
                label: "name",
                value: "id"
              },
              rules: [{
                required: true,
                message: "请选择楼层d",
                trigger: "blur"
              }],
              hide: true,
              viewDisplay: false
            },
            {
              label: "所属房间",
              prop: "roomName",
              addDisplay: false,
              editDisplay: false,
            },
            {
              label: "所属房间",
              prop: "roomId",
              type: "select",
              // slot:true,
              search: true,
              dicUrl: "/api/cyzh-community/room/list?floorId={{key}}&size=500&current=1",
              dicFormatter:(res)=>{
                return res.data.records;//返回字典的层级结构
              },
              // dicFlag: false,
              filterable: true,
              props: {
                label: "name",
                value: "id"
              },
              rules: [{
                required: true,
                message: "请选择房间",
                trigger: "blur"
              }],
              hide: true,
              viewDisplay: false
            },
            {
              label:'手机号码',
              prop:'phone',
              width:120,
              rules: [{
                required: true,
                message: "请输入手机号码",
                trigger: "blur"
              },{
                validator: validatePhone,
                trigger: "blur"
              }]
            },
            {
              label: "生日",
              prop: "birthday",
              type:'date',
              valueFormat:"yyyy-MM-dd",
              hide: true,
              rules: [{
                required: false,
                message: "请输入生日",
                trigger: "blur"
              }]
            },
            // {
            //   label: "民族",
            //   prop: "nation",
            //   hide:true,
            //   rules: [{
            //     required: true,
            //     message: "请输入民族",
            //     trigger: "blur"
            //   }]
            // },
            {
              label: "民族",
              prop: "nation",
              type:'select',
              dicData:DIC.VALUE,
              filterable:true,
              // searchFilterable:true,
              hide:true,
              rules: [{
                required: true,
                message: "请输入民族",
                trigger: "blur"
              }]
            },
            {
              label: "籍贯",
              prop: "nativePlace",
              hide:true,
              rules: [{
                required: false,
                message: "请输入籍贯",
                trigger: "blur"
              }]
            },
            {
              label: "国籍",
              prop: "nationality",
              hide:true,
              type:'select',
              dataType:'number',
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=nationality",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: false,
                message: "请输入国籍",
                trigger: "blur"
              }]
            },
            {
              label: "政治面貌",
              prop: "political",
              hide:true,
              type: 'select',
              dataType:"number",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=political",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: false,
                message: "请选择政治面貌",
                trigger: "blur"
              }]
            },
            {
              label: "婚姻状况",
              prop: "maritalStatus",
              type: 'select',
              dataType:"number",
              hide:true,
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=marital-status",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: false,
                message: "请选择婚姻状况",
                trigger: "blur"
              }]
            },
            {
              label: "教育水平",
              prop: "educationalLevel",
              hide:true,
              type: 'select',
              dataType:"number",
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=educational-level",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: false,
                message: "请选择教育水平",
                trigger: "blur"
              }]
            },
            {
              label: "工作单位",
              prop: "workplace",
              hide:true,
              rules: [{
                required: false,
                message: "请输入工作单位",
                trigger: "blur"
              }]
            },
            {
              label: "小程序openId",
              prop: "openId",
              hide: true,
              display: false,
              rules: [{
                required: false,
                message: "请输入小程序openId",
                trigger: "blur"
              }]
            },
            {
              label: "邮箱",
              prop: "email",
              hide:true,
              rules: [{
                required: false,
                message: "请输入邮箱",
                trigger: "blur"
              }]
            },
            {
              label:"是否会员",
              prop:'isMember',
              type:"select",
              hide:true,
              dataType:'number',
              dicData:[
                {
                  label:'是',
                  value:1
                },{
                  label:'否',
                  value:0
                },{
                  label:'暂无',
                  value:-1
                }
              ],
            },
            {
              label: "人员标签",
              prop: "tags",
              type:'checkbox',
              search:true,
              multiple:true,
              span: 24,
              dataType:'string',
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=person-tag",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              rules: [{
                required: false,
                message: "请输入标签",
                trigger: "blur"
              }]
            },
            {
              label: "备注",
              prop: "remark",
              hide:true,
              rules: [{
                required: false,
                message: "请输入备注",
                trigger: "blur"
              }]
            },
            /*{
              label:'创建时间',
              prop:'createTime',
              type:"datetime",
              span:12,
              search:true,
              valueFormat: 'yyyy-MM-dd HH:mm:ss',
              format: 'yyyy-MM-dd HH:mm:ss',
              defaultTime:['2020-1-1 00:00:00','2021-6-30 23:59:59'],
              // dateDefault: true,
              // searchValue:['2020-1-1 00:00:00','2021-6-30 23:59:59'],
              searchRange:true,
              searchClearable: false,
              rules: [{
                required: false,
                message: "请输入创建时间",
                trigger: "blur"
              }]
            }*/
          ]
        },
        data: []
      };
    },
    watch:{

    },

    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.basicinfo_add, false),
          viewBtn: this.vaildData(this.permission.basicinfo_view, false),
          delBtn: this.vaildData(this.permission.basicinfo_delete, false),
          editBtn: this.vaildData(this.permission.basicinfo_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    methods: {
      selectCallback(row){
        this.form.residentialId = row.id;
        this.form.residentialName = row.name;
        if (this.option.column[6].prop == 'buildingId' && this.option.column[6].dicUrl.indexOf('residentialId') == -1){
          this.option.column[6].dicUrl += '?residentialId=' + this.form.residentialId + '&size=100';
        }
      },
      tagsFormOpen(type,row) {
        this.basicData = row;
        switch (type) {
          case 'elder':
            this.elderTags = true;
            break;
          case 'disabler':
            this.disablerTags = true;
            break;
          case 'keyPerson':
            this.keyPersonTags = true;
            break;
          // case 'household':
          //   this.householdTags = true;
          //   break;
          // case 'enterpriseStaff':
          //   this.enterpriseStaffTags = true;
          //   break;
        }
      },
      tagsDetail(type,row){
        this.basicData = row;
        switch (type) {
          case '高龄老人':
            this.elderTagsdetail = true;
            break;
          case '残障人士':
            this.disablerTagsdetail = true;
            break;
          case '重点人员':
            this.keyPersonTagsdetail = true;
            break;
          // case '常住人员':
          //   this.householdTagsdetail = true;
          //   break;
          // case '企业员工':
          //   this.enterpriseStaffTagsdetail = true;
          //   break;
        }
      },
      rowSave(row, done, loading) {
        row.agencyName = row.$agencyId;
        // row.residentialName = row.$residentialId;
        row.buildingName = row.$buildingId;
        row.unitName = row.$unitId;
        row.floorName = row.$floorId;
        row.roomName = row.$roomId;
        if (row.tags.length == 0) {
          row.tags = '';
        }
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },

       exist(num, arr1) {
        for (var j = 0; j < arr1.length; j++) {
            if (num === arr1[j]) {
              return false; //如果传过来的元素在arr1中能找到相匹配的元素，我们返回fasle
            }
          }
            return true; //如果不能找到相匹配的元素，返回true
       },
      rowUpdate(row, index, done, loading) {
        row.agencyName = row.$agencyId;
        // row.residentialName = row.$residentialId;
        row.buildingName = row.$buildingId;
        row.unitName = row.$unitId;
        row.floorName = row.$floorId;
        row.roomName = row.$roomId;
        if (row.tags.length == 0) {
          row.tags = '';
        }
        if (this.oldForm.tags!=null){
          let oldtags = this.oldForm.tags.split(",");
          let utags = row.tags.split(",");
          let len = oldtags.length;
          for(let i = 0;i < len;i++){
            if (this.exist(oldtags[i],utags)){
              this.delTags.push(oldtags[i]);
            }
          }
        }
        if (this.delTags.length!=0){
          this.confirmInfo = "修改将删除"+this.delTags.toString()+"标签,确认修改？";
        }else {
          this.confirmInfo = "确认修改?";
        }
        this.$confirm(this.confirmInfo, {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(()=> {
        update(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        })});
      },
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelFace(row) {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定要删除选择的人脸?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return delFace(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        this.residentialDisabled = false;
        if (["edit", "view"].includes(type)) {
          this.residentialDisabled = true;
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
            this.oldForm = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {};
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        console.log(params,"搜索条件参数");
        this.onLoad(this.page, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      currentChange(currentPage){
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize){
        this.page.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoad(this.page, this.query);
      },
      onLoad(page, params = {}) {
        this.loading = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      }
    }
  };
</script>

<style>
</style>
