<template>
  <div class="resi-container">
    <!-- <el-card class="resi-card"> -->
    <div class="g-main">
      <el-form :inline="true" class="header_form_box" :model="form" :label-width="'105px'">
        <el-form-item label="居民分类">
          <el-cascader
          ref="categoryAll"
          size="small"
          class="u-item-width-normal"
          v-model.trim="categoryAll" 
          :options="categoryAllList"
          :props="{ multiple: true,checkStrictly: true,emitPath:false}"
          collapse-tags
          clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="政治面貌">
          <el-select v-model.trim="form.partyFlag" class="u-item-width-normal" clearable size="small">
            <template v-for="item in partyList">
              <el-option :label='item.label' :value='item.value'> </el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="健康状态">
          <el-select v-model.trim="form.healthStatus" collapse-tags multiple class="u-item-width-normal" clearable
            size="small">
            <template v-for="item in healthStatusList">
              <el-option :label='item.label' :value='item.value'> </el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="关注人群">
          <el-cascader
          size="small"
          class="u-item-width-normal"
          v-model.trim="form.attentionCrowds" 
          :options="resiClass"
          :props="{ multiple: true,checkStrictly: true,emitPath:false}"
          collapse-tags
          clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="特殊人群">
          <el-select v-model.trim="form.specialCategoryCodes" class="u-item-width-normal" clearable size="small" collapse-tags
            multiple>
            <template v-for="item in specialCategoryList">
              <el-option :label='item.label' :value='item.value'> </el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="就业状态">
          <el-select v-model.trim="form.careerStatus" class="u-item-width-normal" clearable size="small">
            <template v-for="item in careerStatusList">
              <el-option :label='item.label' :value='item.value'> </el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="身份">
          <el-select v-model.trim="form.identity" class="u-item-width-normal" clearable size="small" >
            <template v-for="item in projectStaffList">
              <el-option :label='item.label' :value='item.value'> </el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="人户状况">
          <el-select v-model.trim="form.householdSituation" class="u-item-width-normal" clearable size="small">
            <template v-for="item in household">
              <el-option :label='item.label' :value='item.value'> </el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="人房关系">
          <el-select v-model.trim="form.resiHouseRel" class="u-item-width-normal" clearable size="small">
            <template v-for="item in resiHouseRelList">
              <el-option :label='item.label' :value='item.value'> </el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="名称模糊查询">
          <el-select v-model.trim="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.trim="form[item.value]" class="u-item-width-service" placeholder="请输入" clearable size="small">
          </el-input>
        </el-form-item>
        <el-form-item label="满意度次数">
          <el-select v-model.trim="form.satisfactionNum" class="u-item-width-normal" clearable size="small">
            <template v-for="(item,index) in 6">
              <el-option :label='`${index}次`' :value='index'> </el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="居民年龄">
          <el-input v-model.trim="form.ageStart" @change="handleAgeChange" class="u-item-width-daterange" placeholder="请输入" clearable size="small">
          </el-input>
          <span class="u-data-tag">至</span>
          <el-input v-model.trim="form.ageEnd" @change="handleAgeChange" class="u-item-width-daterange u-data-tag"
            placeholder="请输入" clearable size="small">
          </el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-select v-model.trim="form.gender" class="u-item-width-normal" clearable size="small">
            <el-option label='男' value='1'> </el-option>
            <el-option label='女' value='2'> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文化程度">
          <el-select v-model.trim="form.cultureLevel" class="u-item-width-normal" clearable size="small">
            <template v-for="item in Education">
              <el-option :label='item.label' :value='item.value'> </el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="国籍">
          <el-select v-model.trim="form.nationality" class="u-item-width-normal" clearable size="small">
            <template v-for="item in nationalityList">
              <el-option :label='item.label' :value='item.value'> </el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="民族">
          <el-select v-model.trim="form.nation" class="u-item-width-normal" clearable size="small">
            <template v-for="item in nation">
              <el-option :label='item.label' :value='item.value'> </el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="完整度得分">
          <el-input v-model.trim="form.integrityScoreFrom"  typ="number" @change="informationChange(form.integrityScoreFrom,'from')" class="u-item-width-daterange" placeholder="请输入" clearable size="small">
          </el-input>
          <span class="u-data-tag">至</span>
          <el-input v-model.trim="form.integrityScoreTo"  @change="informationChange(form.integrityScoreTo,'to')"  class="u-item-width-daterange u-data-tag"
            placeholder="请输入" typ="number" clearable size="small">
          </el-input>
        </el-form-item>
        <el-form-item label="更新时间">
          <el-date-picker v-model.trim="form.updateTimeStart" type="datetime" size="small" class="u-item-width-daterange"
            value-format="yyyy-MM-dd HH:mm:ss" placeholder="开始日期" :picker-options="pickerOptionsStart">
          </el-date-picker>
          <span class="u-data-tag">至</span>
          <el-date-picker v-model.trim="form.updateTimeEnd" type="datetime" size="small" value-format="yyyy-MM-dd HH:mm:ss"
            class="u-item-width-daterange u-data-tag" placeholder="结束日期" :picker-options="pickerOptionsEnd">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <span style="width:100px;text-align: right;padding-right:14px;display: inline-block; ">所属组织:</span>
          <el-cascader class="u-item-width-normal"
                       size="small"
                       ref="myCascader"
                       v-model="form.agencyId"
                       :options="orgOptions"
                       :props="orgOptionProps"
                       :show-all-levels="false"
                       @change="handleChangeAgency"
                       clearable></el-cascader>
        </el-form-item>
        <el-form-item prop="villageId">
          <div class="resi-cell">
            <div class="resi-cell-value">
              <span style="width:100px;text-align: right;padding-right:14px;display: inline-block; ">所属房屋:</span>
              <el-select v-model.trim="form.villageId"
                         placeholder="请选择小区"
                         size="small"
                         filterable
                         clearable
                         class="u-item-width-communitycascader"
                         @clear="handleClearVillage"
                         @change="handleChangeV"
                         v-el-select-loadmore="loadmore"
                         >
                <el-option v-for="item in optionsV"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
              <el-select v-model.trim="form.buildId"
                         placeholder="楼号"
                         size="small"
                         filterable
                         clearable
                         style="margin-left: 5px"
                         class="u-item-width-buildcascader"
                         :disabled="changeVDisabled"
                         @clear="handleClearBuild"
                         @change="handleChangeB">
                <el-option v-for="item in optionsB"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
              <el-select v-model.trim="form.unitId"
                         :disabled="changeBDisabled"
                         placeholder="单元"
                         size="small"
                         filterable
                         clearable
                         style="margin-left: 5px"
                         class="u-item-width-buildcascader"
                         @click="handleClearDan"
                         @change="handleChangeD">
                <el-option v-for="item in optionsD"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
              <el-select v-model.trim="form.homeId"
                         :disabled="changeDDisabled"
                         placeholder="房号"
                         size="small"
                         filterable
                         clearable
                         style="margin-left: 5px"
                         class="u-item-width-buildcascader">
                <el-option v-for="item in optionsH"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model.trim="form.remark" placeholder="请输入" size="small" class="u-item-width-normal"
            clearable></el-input>
        </el-form-item>
      </el-form>
    </div>
    <el-row v-if="showSmartSearchForm" class="resi-row-more f-m0">
      <el-col :span="24">
        <el-button v-for="btnItem in btnList" :key="btnItem.index" size="small"
          :class="selBtnIndex === btnItem.index ? 'diy-button--white' : 'diy-button--common'"
          @click="handelSelSmartBtn(btnItem.index)">{{ btnItem.name }}</el-button>

      </el-col>
      <el-col>
        <smart-search-rule ref="ref_rule" :formType="formType"></smart-search-rule>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import inputRange from './rangeInput.vue'
import smartSearchRule from './smartSearchRule.vue'
export default {
  name: 'ResiSearch',
  components: {
    inputRange, smartSearchRule
  },
  props: {
    formList: {
      type: Array,
      default: () => []
    },
    columnName: {
      type: String,
      default: ''
    },
    showGrid: {
      type: Boolean,
      default: false
    },
    isArrow: {
      type: Boolean,
      default: false
    }
  },
  data() {
    let initForm = (arr, columnName) => {
      let _form = {}
      arr.forEach((item) => {
        if (item.itemType == 'checkbox') _form[item.columnName] = []
        else if (item.queryType == 'resi_category' && columnName) {
          _form[item.columnName] = [columnName]
        } else if (columnName && columnName === item.columnName) _form[item.columnName] = '1'
        else if (item.itemType == 'inputRange') _form[item.columnName] = { start: '', end: '' }
        else _form[item.columnName] = ''
      })
      return _form
    }
    let itemList = this.formList.map(item => {
      if (item.itemType == 'inputRange' && item.funType == 'agetoyear') {
        item.columnName = 'age'
      }
      return {
        ...item
      }
    })


    let form = (itemList, this.columnName)
    let tempFormList = itemList.map(item => {

      return {
        ...item,
        isChange: (item.queryType == 'resi_category' && this.columnName) || this.columnName === item.columnName ? true : false
      }
    })
    let constForm = {

    }
    let orgOptionProps = {
      multiple: false,
      value: 'agencyId',
      label: 'agencyName',
      children: 'subAgencyList',
      checkStrictly: true
    }
    let endDisabledDate = (time) => {//这个关键属性我们一定要写在data的里面并且return的外面，这是动态改变区间的关键
      let nowData = Date.now()
      if (this.updateStartDate) {
        let startTime = new Date(this.updateStartDate)
        return time.getTime() > nowData || time.getTime() < startTime || time.getTime() === startTime
      } else {
        return time.getTime() > nowData
      }

    }
    let startDisabledDate = (time) => {//这个关键属性我们一定要写在data的里面并且return的外面，这是动态改变区间的关键
      let nowData = Date.now()
      return time.getTime() > nowData
    }

    return {
      categoryAll:[],
      categoryAllList:[
        {
          label:'群众',
          value:'partyFlag0',
        },{
          label:'流动人员',
          value:'FLOATING_FLAG',
        },{
          label:'党员',
          value:'partyFlag1',
        },{
          label:'共青团员',
          value:'partyFlag2',
        },{
          label:'残疾人',
          value:'DISABILITY_FLAG',
        },{
          label:'大病',
          value:'SERIOUS_ILLNESS_FLAG',
        },{
          label:'慢病',
          value:'CHRONIC_DISEASE_FLAG',
        },{
          label:'老年人',
          value:'OLD_PEOPLE_FLAG',
          children:[
          {
              label: "失能老人",
              value: "DISABLED_FLAG",
          }, {
              label: "空巢老人",
              value: "EMPTY_NESTER_FLAG",
          },
          {
              label: "失智老人",
              value: "DEMENTED_FLAG",
          },
          {
              label: "独居老人",
              value: "LIVE_ALONE_FLAG",
          },
          {
              label: "普通老年人",
              value: "OLD_PEOPLE_FLAG",
          }
          ]
        },{
          label:'低保人员',
          value:'SUBSISTENCE_ALLOWANCE_FLAG',
        },{
          label:'退役军人',
          value:'VETERAN_FLAG',
        },{
          label:'保障房人员',
          value:'ENSURE_HOUSE_FLAG',
        },{
          label:'育龄妇女',
          value:'FERTILE_WOMAN_FLAG',
        },{
          label:'特扶人员',
          value:'SPECIAL_SUPPORT_FLAG',
        },{
          label: "留守儿童",
          value: "LBC_FLAG",
          children: null
        },{
          label: "艾滋病人员",
          value: "AIDS_FLAG",
          children: null
        },{
          label:'失业人员',
          value:'UNEMPLOYED_FLAG',
        },{
          label:'新阶层人士',
          value:'NEW_STRATUM_FLAG',
        },{
        label: "新就业群体",
        value: "NEG_FLAG",
        "children": null    
      },{
         label:'安置帮教人员',
          value:'anzhibangjiao',
        },{
          label:'吸毒人员',
          value:'xidurenyuan',
        },{
          label:'社区矫正人员',
          value:'shequjiaozheng',
        },{
          label:'不良青少年',
          value:'buliangqingshaonian',
        },{
          label:'肇事肇祸精神障碍患者',
          value:'zhaoshizhaohuojingshenbing',
        },{
          label:'邪教人员',
          value:'xiejiaorenyuan',
        },{
          label:'信访人员',
          value:'xinfangrenyaun',
        },{
          label:'统战人员',
          value:'tongzhanrenyuan',
        },{
          label:'志愿者',
          value:'VOLUNTEER_FLAG',
        },{
          label:'网格员',
          value:'GRID_MEMBER_FLAG',
        },{
          label:'楼长',
          value:'BUILDING_CHIEF_FLAG',
        },{
          label:'单元长',
          value:'UNIT_CHIEF_FLAG',
        },{
          label:'公益岗',
          value:'PUBLIC_WELFARE_FLAG',
        }
      ],
      boxHeight: true,
      pageLoading: false,
      openSearch: false,
      basicType: "name",
      basicInfoList: [
        {
          label: '姓名',
          value: 'name'
        },
        {
          label: '联系电话',
          value: 'mobile'
        },
        {
          label: '证件号',
          value: 'idNum'
        },
        {
          label: '籍贯',
          value: 'nativePlace'
        },
        {
          label: '备注',
          value: 'remark'
        }
      ],
      optionsV: [],
      optionsB: [],
      optionsH: [],
      optionsD: [],
      orgOptions: [],
      orgOptionProps,
      agencyIdArray: [],
      Education: [],
      nation: [],
      nationalityList: [],
      household: [],
      resiClass: [
    {
        "label": "老年人",
        "value": "OLD_PEOPLE_FLAG",
        "children": [
        {
        "label": "失能老人",
        "value": "DISABLED_FLAG",
        "children": null
    }, {
        "label": "空巢老人",
        "value": "EMPTY_NESTER_FLAG",
        "children": null
    },
    {
        "label": "失智老人",
        "value": "DEMENTED_FLAG",
        "children": null
    },
    {
        "label": "独居老人",
        "value": "LIVE_ALONE_FLAG",
        "children": null
    },
    {
        "label": "普通老年人",
        "value": "OLD_PEOPLE_FLAG",
        "children": null
    },
        ]
    },
    {
        "label": "低保人员",
        "value": "SUBSISTENCE_ALLOWANCE_FLAG",
        "children": null
    },
   
    {
        "label": "保障房人员",
        "value": "ENSURE_HOUSE_FLAG",
        "children": null
    },
    {
        "label": "退役军人",
        "value": "VETERAN_FLAG",
        "children": null
    },
    {
        "label": "育龄妇女",
        "value": "FERTILE_WOMAN_FLAG",
        "children": null
    },
    {
        "label": "特扶人员",
        "value": "SPECIAL_SUPPORT_FLAG",
        "children": null
    },{
      "label": "新阶层人士",
        "value": "NEW_STRATUM_FLAG",
        "children": null
    },{
      "label": "留守儿童",
        "value": "LBC_FLAG",
        "children": null
    },{
      "label": "艾滋病人员",
        "value": "AIDS_FLAG",
        "children": null
    },{
      "label": "新就业群体",
        "value": "NEG_FLAG",
        "children": null
    },{
      "label": "流动人员",
        "value": "FLOATING_FLAG",
        "children": null
    },{
      "label": "失业人员",
        "value": "UNEMPLOYED_FLAG",
        "children": null
    }
],
      itemList,
      fixedList: [],
      constForm,
      partyList: [
        {
          label: '群众',
          value: 0
        },
        {
          label: '党员',
          value: 1
        },
        {
          label: '共青团员',
          value: 2
        }
      ],
      resiHouseRelList: [
        {
          label: '自住',
          value: 0
        },
        {
          label: '租住',
          value: 1
        }
      ],
      healthStatusList: [
        {
          label: '残疾',
          value: 'DISABILITY_FLAG'
        },
        {
          label: '大病',
          value: 'SERIOUS_ILLNESS_FLAG'
        },
        {
          label: '慢病',
          value: 'CHRONIC_DISEASE_FLAG'
        }
      ],
      projectStaffList: [
      {
          label: '志愿者',
          value: 'VOLUNTEER_FLAG'
        },{
          label: '网格员',
          value: 'GRID_MEMBER_FLAG'
        },
        {
          label: '楼长',
          value: 'BUILDING_CHIEF_FLAG'
        },
        {
          label: '单元长',
          value: 'UNIT_CHIEF_FLAG'
        },
        {
          label: '公益岗',
          value: 'PUBLIC_WELFARE_FLAG'
        }
      ],
      specialCategoryList: [
        {
          label: "安置帮教",
          value: "anzhibangjiao",
          children: null
        },
        {
          label: "吸毒人员",
          value: "xidurenyuan",
          children: null
        },
        {
          label: "社区矫正",
          value: "shequjiaozheng",
          children: null
        },
        {
          label: "不良青少年",
          value: "buliangqingshaonian",
          children: null
        },
        {
          label: "肇事肇祸精神病",
          value: "zhaoshizhaohuojingshenbing",
          children: null
        },
        {
          label: "邪教人员",
          value: "xiejiaorenyuan",
          children: null
        },
        {
          label: "统战人员",
          value: "tongzhanrenyuan",
          children: null
        },
        {
          label: "信访人员",
          value: "xinfangrenyaun",
          children: null
        }
      ],
      careerStatusList: [],
      form: {
        name: '',
        mobile: '',
        updateCategory:null,
        satisfactionNum:null,
        idNum: '',
        birthdayStart: '',
        birthdayEnd: '',
        ageStart: '',
        ageEnd: '',
        integrityScoreFrom: null,//居民信息完整度はじめ
        integrityScoreTo: null,//居民信息完整度end
        identity:null,
        gender: '',
        cultureLevel: '',
        localResidenceFlag: '',
        householdSituation: '',
        nation: '',
        agencyId: '',
        buildId: '',
        homeId: '',
        unitId: '',
        gridId: '',
        villageId: '',
        attentionCrowds: [],
        healthStatus: [],
        nationality: '',
        resiHouseRel: '',
        partyFlag: '',
        updateTimeStart: '',
        updateTimeEnd: '',
        specialCategoryCodes: [],
        remark: '',
        level: '',
        orgType: ''
      },
      tempFormList,
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },

      queryType: {
        'agencyId	': 'like'
      },
      sarr: [],

      showSmartSearchForm: false,
      formType: 'add',
      selBtnIndex: 1,
      btnList: [
        {
          name: '自定义查询',
          index: 1,

        },
        {
          name: '租户',
          index: 2,
          ruleList: [
            {
              selSmartType: 'house',
              nextLogicalRel: "",
              nextLogicalRelName: "",
              personRule: {
                ruleDesc: '',//规则描述文字，例如：基础信息性别等于女
                itemGroupId: '',
                itemId: '',
                queryType: '',
                colTable: '',
                colKey: '',
                colVal: '',

                itemList: [],
                colType: '',//详细参数的组件类型
                colOption: [],
                itemGroupName: '',
                itemLabel: '',
                queryTypeName: '',
                colValLabel: '',
              },
              houseRule: {
                colKey: "RENT_FLAG",
                colTable: "ic_house",
                colVal: "1",
                colValLabel: "出租",
                itemGroupId: null,
                itemGroupName: "房屋信息",
                itemId: null,
                itemLabel: "房屋状态",
                nextLogicalRel: "",
                nextLogicalRelName: "",
                queryType: "=",
                queryTypeName: "等于",
                ruleDesc: "房屋信息房屋状态等于出租",

              },
            },
          ]
        },


      ],
      endPickerOptions: {
        disabledDate: endDisabledDate
      },
      startPickerOptions: {
        disabledDate: startDisabledDate
      },
      timer: {
        startPickerTime: '',
        endPickerTime: ''
      },
      pickerOptionsStart: {
        disabledDate: time => {
          let dateVal = this.form.birthdayEnd
          if (dateVal) {
            return time.getTime() > new Date(dateVal).getTime();
          } else {
            return time.getTime() > Date.now() - 8.64e6;
          }
        }
      },
      pickerOptionsEnd: {
        disabledDate: time => {
          let nowData = Date.now();
          if (this.form.birthdayStart) {
            let birthdayStartTime = new Date(this.form.birthdayStart);
            return (
              time.getTime() < birthdayStartTime - 24 * 60 * 60 * 1000 ||
              time.getTime() > nowData
            );
          } else {
            return (time.getTime() > nowData || time.getTime() === nowData);
          }
        }
      },
      optionsVPageNo: 1,
    }
  },
  computed: {
    sliceList() {
      return function (data, count) {
        // 接收
        if (data !== undefined) {
          let index = 0
          let arrTemp = []
          for (let i = 0; i < data.length; i++) {
            index = parseInt(0)
            if (arrTemp.length <= index) {
              arrTemp.push([])
            }
            arrTemp[index].push(data[i])
          }
          return arrTemp
        }
      }
    },
    changeVDisabled() {
      return !this.form.villageId
    },
    changeBDisabled() {
      return !this.form.buildId
    },
    changeDDisabled() {
      return !this.form.unitId
    },
  },
  watch: {
    form: {
      handler(val, val2) {
        for (let n in val) {
          if (this.constForm[n] !== val[n]) {
            this.handleChangeForm(n)
          }
        }
        this.constForm = { ...val }
      },
      deep: true
    },
    timer: {
      handler(newVal) {
        this.handelWatchStartDate(newVal)
      },
      deep: true,
      immediate: true
    },
    categoryAll: {
      handler(val, val2) {
          this.handleCategoryChange(val, val2)
      },
      deep: true
    },
  },
  directives: {
    "el-select-loadmore": {
      bind(el, binding) {
        const SELECTWRAP_DOM = el.querySelector(
          ".el-select-dropdown .el-select-dropdown__wrap"
        );
        SELECTWRAP_DOM.addEventListener("scroll", function () {
          const condition =
            this.scrollHeight - this.scrollTop <= this.clientHeight;
          if (condition) {
            binding.value();
          }
        });
      },
    },
  },
  created() {
    this.getOrgTreeList()
    this.getEducation()
    this.getDictList()
    this.getHousehold()
    this.getNationality()
    this.getCareerStatus()
    if (this.columnName) this.handleChangeForm(this.columnName)
  },
  mounted(){
    this.$EventBus.$on('handleClickResiTree', async (val) => {
           if(val.type === 'agency'){
              this.form.agencyId = val.id;
              this.optionsV = [];
              this.form.villageId = '';
              this.form.buildId = '';
             await this.getValiheList();
           }else if(val.type === 'neighborHood'){
            this.form.villageId = val.id;
            await this.handleChangeV(val.id)
            this.form.buildId = '';
           }else if(val.type === 'building'){
            this.form.buildId = val.id;
            await this.handleChangeB(val.id)
           }
    })
  },
  methods: {
    handleCategoryChange(newVal, oldVal) {
      let formCopy = JSON.parse(JSON.stringify(this.form));

      // 找出被取消选中的值
      let cancelledValues = oldVal.filter(val => !newVal.includes(val));

      // 处理取消选中的值
      cancelledValues.forEach(val => {
        if (['partyFlag0', 'partyFlag1', 'partyFlag2'].includes(val)) {
          formCopy.partyFlag = null;
        } else if (['FLOATING_FLAG', 'OLD_PEOPLE_FLAG','OLD_PEOPLE_FLAG', 'LIVE_ALONE_FLAG', 'DEMENTED_FLAG', 'EMPTY_NESTER_FLAG', 'DISABLED_FLAG', 'SUBSISTENCE_ALLOWANCE_FLAG', 'ENSURE_HOUSE_FLAG', 'VETERAN_FLAG', 'FERTILE_WOMAN_FLAG', 'SPECIAL_SUPPORT_FLAG', 'NEW_STRATUM_FLAG','NEG_FLAG', 'LBC_FLAG', 'AIDS_FLAG'].includes(val)) {
          formCopy.attentionCrowds = formCopy.attentionCrowds.filter(item => item !== val);
        } else if (['DISABILITY_FLAG', 'SERIOUS_ILLNESS_FLAG', 'CHRONIC_DISEASE_FLAG'].includes(val)) {
          formCopy.healthStatus = formCopy.healthStatus.filter(item => item !== val);
        } else if (['anzhibangjiao', 'xidurenyuan', 'shequjiaozheng', 'buliangqingshaonian', 'zhaoshizhaohuojingshenbing', 'xiejiaorenyuan', 'tongzhanrenyuan', 'xinfangrenyaun'].includes(val)) {
          formCopy.specialCategoryCodes = formCopy.specialCategoryCodes.filter(item => item !== val);
        } else if (['VOLUNTEER_FLAG', 'BUILDING_CHIEF_FLAG', 'UNIT_CHIEF_FLAG', 'PUBLIC_WELFARE_FLAG','GRID_MEMBER_FLAG'].includes(val)) {
          formCopy.identity = null;
        } else if (val === 'UNEMPLOYED_FLAG') {
          formCopy.careerStatus = null;
        }
      });

      // 处理新选中的值
      newVal.forEach(val => {
        if (val === 'partyFlag0' || val === 'partyFlag1' || val === 'partyFlag2') {
          formCopy.partyFlag = val === 'partyFlag0' ? 0 : val === 'partyFlag1' ? 1 : 2;
        } else if (['FLOATING_FLAG', 'OLD_PEOPLE_FLAG','OLD_PEOPLE_FLAG', 'LIVE_ALONE_FLAG', 'DEMENTED_FLAG', 'EMPTY_NESTER_FLAG', 'DISABLED_FLAG' ,'SUBSISTENCE_ALLOWANCE_FLAG', 'ENSURE_HOUSE_FLAG', 'VETERAN_FLAG', 'FERTILE_WOMAN_FLAG', 'SPECIAL_SUPPORT_FLAG', 'NEW_STRATUM_FLAG','NEG_FLAG', 'LBC_FLAG', 'AIDS_FLAG'].includes(val)) {
          if (!formCopy.attentionCrowds.includes(val)) {
            formCopy.attentionCrowds.push(val);
          }
        } else if (['DISABILITY_FLAG', 'SERIOUS_ILLNESS_FLAG', 'CHRONIC_DISEASE_FLAG'].includes(val)) {
          if (!formCopy.healthStatus.includes(val)) {
            formCopy.healthStatus.push(val);
          }
        } else if (['anzhibangjiao', 'xidurenyuan', 'shequjiaozheng', 'buliangqingshaonian', 'zhaoshizhaohuojingshenbing', 'xiejiaorenyuan', 'tongzhanrenyuan', 'xinfangrenyaun'].includes(val)) {
          if (!formCopy.specialCategoryCodes.includes(val)) {
            formCopy.specialCategoryCodes.push(val);
          }
        } else if (['VOLUNTEER_FLAG', 'BUILDING_CHIEF_FLAG', 'UNIT_CHIEF_FLAG', 'PUBLIC_WELFARE_FLAG','GRID_MEMBER_FLAG'].includes(val)) {
          formCopy.identity = val;
        } else if (val === 'UNEMPLOYED_FLAG') {
          formCopy.careerStatus = '0';
        }
      });

      // 更新表单数据
      this.form = formCopy;
    },

    handelWatchStartDate(val) {
      return val
    },
    initForm() {
      this.formList.forEach((item) => {
        this.$set(this.form, item.columnName, '')
      })
    },
    computdSpan(len) {
      return len == 1 ? 24 : 6
    },
    handleClearVillage() {
      this.form.buildId = ''
      this.form.homeId = ''
    },
    handleClearBuild() {
      this.form.buildId = ''
      this.form.unitId = ''
      this.form.homeId = ''
    },
    handleClearDan() {
      this.form.unitId = ''
      this.form.homeId = ''
    },
    handleSearchFrom() {
      this.$emit('handleSearchFrom', '')
    },
    resetForm(formName) {
      for (const n in this.form) {
        if (n == 'age') {
          this.form.age = {
            start: '',
            end: ''
          }
        } else if (n == 'BIRTHDAY') {
          this.form.BIRTHDAY = []
          this.timer.startPickerTime = null
          this.timer.endPickerTime = null
        } else if (typeof this.form[n] == 'object') this.form[n] = []
        else this.form[n] = ''
      }
      this.agencyIdArray = []
      this.$emit('search', [])
    },
    handleAgeChange() {
      if (this.form.ageStart&&this.form.ageEnd) {
        if (Number(this.form.ageStart) > Number(this.form.ageEnd)) {
          this.$message.warning('结束年龄不能小于开始年龄')
        }
      }
    },
    informationChange(val,type) {
      if(isNaN(val)){
        this.$message.warning('请输入数字');
        if(type === 'from'){
          this.form.integrityScoreFrom = null;
        }else{
          this.form.integrityScoreTo = null;
        }
      }
      if (this.form.integrityScoreFrom&&this.form.integrityScoreTo) {
        if (Number(this.form.integrityScoreFrom) >Number(this.form.integrityScoreTo)) {
          this.$message.warning('结束分数不能小于开始分数')
        }
      }
    },
    handleChangeAgency(val) {
      this.sarr = []
      this.getLastItem(
        this.orgOptions,
        val,
        "agencyId"
      );
      this.form.agencyId=this.sarr[this.sarr.length - 1].agencyId
      this.form.level = this.sarr[this.sarr.length - 1].level;
      this.getValiheList()
    },
    getLastItem(list, vals, key) {
      let LIST = list || [];
      for (let item of LIST) {
        for (let i of vals) {
          if (item[key] === i) {
            this.sarr.push(item);
          } else {
            this.getLastItem(item.subAgencyList, vals, key);
          }
        }
      }
    },

    handleChangeGrid(val) {
      this.form.villageId = ''
      this.form.buildId = ''
      this.form.unitId = ''
      this.form.homeId = ''
      this.getValiheList()
    },
    handleChangeV(val) {
      this.form.buildId = ''
      this.form.unitId = ''
      this.form.homeId = ''
      this.getBuildList()
    },
    handleChangeB(val) {
      this.form.unitId = ''
      this.form.homeId = ''
      this.getUniList()
    },
    handleChangeD(val) {
      this.form.homeId = ''
      this.getHouseList()
    },
    // 监听基础form
    handleChangeForm(val) {
      for (let n in this.fixedForm) {
        if (n === val) {
          if (this.fixedList.length > 0) {
            let _item = {}
            let hasVal = false
            this.fixedList.forEach((item, index) => {
              if (item.columnName == val) {
                hasVal = true
                item.columnValue[0] = this.form[val]
                if (!this.form[val]) this.fixedList.splice(index, 1)
              } else {
                _item = {
                  queryType: this.queryType[val] ? this.queryType[val] : 'equal',//'equal',
                  tableName: 'ic_resi_user',
                  columnName: val,
                  columnValue: [this.form[val]]
                }
                // this.$set(this.fixedList, index, _item)
              }
            })
            if (Object.keys(_item).length > 0 && !hasVal) this.fixedList.push(_item)
          } else {
            this.$set(this.fixedList, 0, {
              queryType: this.queryType[val] ? this.queryType[val] : 'equal',//'equal',
              tableName: 'ic_resi_user',
              columnName: val,
              columnValue: [this.form[val]]
            })
          }
        }
      }
      this.tempFormList.forEach((item) => {
        if (item.columnName === val) item.isChange = true
      })
    },
    getOrgTreeList() {
      this.$http
        .post('/gov/org/customeragency/agencygridtree', {})
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            this.orgOptions = []
            this.orgOptions.push(res.data)
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
    },

    loadmore() {
      this.optionsVPageNo++;
      this.getValiheList();
    },
    getValiheList() {
      this.$http
        .post('/actual/base/communityQuarters/listQuartersOptions', {
          gridId: this.form.agencyId,
          agencyId: this.$store.state.user.agencyId,
          pageNo: this.optionsVPageNo,
          pageSize: 20
          // agencyId: user.agencyId
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            this.optionsV = [...this.optionsV, ...res.data];
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
    },
    getBuildList() {
      this.$http
        .post('/actual/base/communityBuilding/buildingoption', {
          quartersId: this.form.villageId
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            this.optionsB = res.data
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
    },
    getUniList() {
      this.$http
        .post('/actual/base/communityBuildingUnit/unitoption', {
          buildingId: this.form.buildId
        })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            this.optionsD = res.data
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
    },
    getHouseList() {
      this.$http
        .post('/actual/base/communityHouse/houseoption', { buildingId: this.form.buildId, unitId: this.form.unitId })
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {
            this.optionsH = res.data
          }
        })
        .catch(() => {
          return this.$message.error('网络错误')
        })
    },
    getTreeData(data) {
      if (!Array.isArray(data)) return [];
      let arr = data.map((item) => {
        let _item = {};
        if (item.children) {
          if (item.children.length === 0)
            _item = { ...item, children: undefined };
          else _item = { ...item, children: this.getTreeData(item.children) };
        } else {
          _item = { ...item };
        }
        return _item;
      });
      return arr;
    },
    async getEducation() {
      try {
        let { data } = await this.$http.post('sys/dict/data/education', { formCode: "resi_base_info" })
        data.data = this.getTreeData(data.data)
        this.Education = data.data
      } catch (error) {
        console.log(error, '获取民族字典');
      }

    },
    async getDictList() {
      try {
        const { data } = await this.$http.post('sys/dict/data/nation', { formCode: "resi_base_info" })
        this.nation = data.data

      } catch (error) {
        console.log(error, '获取民族字典');
      }

    },
    async getNationality() {
      try {
        const { data } = await this.$http.post('sys/dict/data/dictlist', { 'dictType': 'nationality' })
        this.nationalityList = data.data
      } catch (error) {
        console.log(error, '获取国籍字典');
      }
    },
    async getCareerStatus() {
      try {
        const { data } = await this.$http.post('sys/dict/data/dictlist', { 'dictType': 'career_status' })
        this.careerStatusList = data.data
      } catch (error) {
        console.log(error, '获取国籍字典');
      }
    },

    async getHousehold() {
      try {
        const { data } = await this.$http.post('sys/dict/data/dictlist', { 'dictType': 'household_situation' })
        this.household = data.data
      } catch (error) {
        console.log(error, '获取人户状况字典');
      }
    },
  
    computedBirth(age) {
      let now = new Date();
      let nowYear = now.getFullYear();
      let nowMonth = now.getMonth() + 1;
      let nowDay = now.getDate(); // 按照减法原理，先day相减，不够向month借；然后month相减，不够向year借；最后year相减。
      let subYear = nowYear - age
      if (nowMonth < 10) {
        nowMonth = '0' + nowMonth
      }
      if (nowDay < 10) {
        nowDay = '0' + nowDay
      }
      return subYear + '-' + nowMonth + '-' + nowDay
    },
    computedBirth1(age) {
      let now = new Date();
      let nowYear = now.getFullYear();
      let nowMonth = now.getMonth() + 1;
      let nowDay = now.getDate(); // 按照减法原理，先day相减，不够向month借；然后month相减，不够向year借；最后year相减。
      let subYear = nowYear - age
      if (nowMonth < 10) {
        nowMonth = '0' + nowMonth
      }
      if (nowDay < 10) {
        nowDay = '0' + nowDay
      }
      return subYear - 1 + '-' + nowMonth + '-' + nowDay
    },
    handelClickBasicType() {
      this.form.name = '';
      this.form.mobile = '';
      this.form.idNum = '';
      this.form.nativePlace = '';
      this.form.remark = '';
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/scss/modules/management/list-main.scss";

.header_form_box {
  display: flex;
  flex-wrap: wrap;
}

.resi-search {
  padding-bottom: 14px;

  .el-col {
    text-align: right;
  }
}

.resi-container .resi-cell {
  display: flex;
  align-items: center;

  .resi-cell-label {
    flex-shrink: 0;
    min-width: 70px;
    box-sizing: border-box;
    margin-right: 15px;
    text-align: right;
    // line-height: 32;
  }

  .resi-cell-label1 {
    width: max-content;
  }

  .resi-cell-value-radio {
    display: flex;
    align-items: center;
    min-height: 32px;
  }

  .resi-cell-input {
    max-width: 200px;
  }

  .resi-cell--daterange {
    max-width: 240px;
  }

  .el-form--inline {
    ::v-deep .el-form-item {
      margin-right: 0px !important;
    }
  }

  .resi-cell-select {
    max-width: 200px;
    box-sizing: border-box;

    &-middle {
      width: 130px;
    }

    &-small {
      width: 88px;
    }
  }

  .resi-cell-select:last-child {
    margin-right: 0;
  }
}
</style>
