<template>
  <div>
    <div class="dialog-h-content scroll-h"
         :class="{ 'visiual-form': source === 'visiual' }">
      <el-form ref="ref_add_form"
               :inline="true"
               :model="formData"
               :rules="dataRule"
               class="div_form">

        <el-row>
          <el-col :span="24">
            <div class="info-prop"
                 v-if="formType == 'detail'">
              <span class="info-title-2">所属组织: </span>
              <span>{{ formData.agencyName || "--" }}</span>
            </div>
            <el-form-item v-else
                          label="所属组织"
                          :label-width="labelWidth"
                          prop="agencyId">
              <el-cascader v-if="formType == 'add'"
                           ref="ref_cascader_agency"
                           class="width-two"
                           v-model="formData.agencyId"
                           :options="optionsA"
                           @change="handleChangeAngency"
                           :props="{ checkStrictly: true, emitPath: false,children:'subAgencyList',label:'agencyName',value:'agencyId'}"
                           clearable />

              <span v-else>{{ formData.agencyName || "--" }}</span>

            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-col :span="12">
            <div class="info-prop"
                 v-if="formType == 'detail'">
              <span class="info-title-2">姓名: </span>
              <span>{{ formData.name || "--" }}</span>
            </div>
            <el-form-item :label-width="labelWidth"
                          label="姓名"
                          prop="name"
                          v-else>
              <el-input v-model="formData.name"
                        placeholder="请输入"
                        clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <div class="info-prop"
                 v-if="formType == 'detail'">
              <span class="info-title-2">联系电话: </span>
              <span>{{ formData.mobile || "--" }}</span>
            </div>
            <el-form-item :label-width="labelWidth"
                          label="联系电话"
                          v-else>
              <el-input v-model="formData.mobile"
                        placeholder="请输入"
                        clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <div class="info-prop"
                 v-if="formType == 'detail'">
              <span class="info-title-2">证件类型: </span>
              <span>{{ idTypeName(formData.idType)  }}</span>
            </div>
            <el-form-item :label-width="labelWidth"
                          label="证件类型"
                          prop="idType"
                          v-else>
              <el-select v-model="formData.idType"
                         clearable>
                <el-option v-for="item in idTypeList"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <div class="info-prop"
                 v-if="formType == 'detail'">
              <span class="info-title-2">证件号: </span>
              <span>{{ formData.idNum || "--" }}</span>
            </div>
            <el-form-item :label-width="labelWidth"
                          label="证件号"
                          prop="idNum"
                          v-else>
              <el-input v-model="formData.idNum"
                        placeholder="请输入"
                        clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <div class="info-prop"
                 v-if="formType == 'detail'">
              <span class="info-title-2">出生日期: </span>
              <span>{{formData.birthday||'--'}}</span>
            </div>
            <el-form-item :label-width="labelWidth"
                          label="出生日期"
                          v-else>
              <el-date-picker v-model="formData.birthday"
                              type="date"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="选择日期"
                              style="width: 202px"
                              clearable>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <div class="info-prop"
                 v-if="formType == 'detail'">
              <span class="info-title-2">性别: </span>
              <span>{{
                formData.gender
                  ? formData.gender == "1"
                    ? "男"
                    : formData.gender == "2"
                    ? "女"
                    : "--"
                  : "--"
              }}</span>
            </div>
            <el-form-item :label-width="labelWidth"
                          label="性别"
                          v-else>
              <el-select v-model="formData.gender"
                         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-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <div class="info-prop"
                 v-if="formType == 'detail'">
              <span class="info-title-2">民族: </span>
              <span>{{ nationName(formData.nation) }}</span>
            </div>
            <el-form-item :label-width="labelWidth"
                          label="民族"
                          v-else>
              <el-select v-model="formData.nation"
                         clearable>
                <el-option v-for="item in dicts.nationList"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <div class="info-prop"
                 v-if="formType == 'detail'">
              <span class="info-title-2">本地户籍: </span>
              <span>{{
                formData.localResidenceFlag != null
                  ? formData.localResidenceFlag == 1
                    ? "是"
                    : formData.gender == 0
                    ? "否"
                    : "--"
                  : "--"
              }}</span>
            </div>
            <el-form-item :label-width="labelWidth"
                          label="本地户籍"
                          v-else>
              <el-select v-model="formData.localResidenceFlag"
                         clearable>
                <el-option v-for="item in binaryOptionList"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <div class="info-prop"
                 v-if="formType == 'detail'">
              <span class="info-title-2">户籍地址: </span>
              <span>{{ formData.placeOfDomicile || "--" }}</span>
            </div>
            <el-form-item :label-width="labelWidth"
                          label="户籍地址"
                          class="wd-wr"
                          v-else>
              <el-input v-model="formData.placeOfDomicile"
                        placeholder="请输入"
                        clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <div class="info-prop"
                 v-if="formType == 'detail'">
              <span class="info-title-2">现居地址: </span>
              <span>{{ formData.currentResidence || "--" }}</span>
            </div>
            <el-form-item :label-width="labelWidth"
                          label="现居地址"
                          class="wd-wr"
                          v-else>
              <el-input v-model="formData.currentResidence"
                        placeholder="请输入"
                        clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <div class="info-prop"
                 v-if="formType == 'detail'">
              <span class="info-title-2">婚姻状况: </span>
              <span>{{ marriageName(formData.marriage) }}</span>
            </div>
            <el-form-item :label-width="labelWidth"
                          label="婚姻状况"
                          v-else>
              <el-select v-model="formData.marriage"
                         placeholder="请输入"
                         size="small"
                         class="u-item-width-normal"
                         clearable>
                <el-option v-for="item in dicts.marriageList"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <div class="info-prop"
                 v-if="formType == 'detail'">
              <span class="info-title-2">银行卡号: </span>
              <span>{{  formData.bankAccount||'--' }}</span>
            </div>
            <el-form-item :label-width="labelWidth"
                          label="银行卡号"
                          v-else>
              <el-input v-model="formData.bankAccount"
                        placeholder="请输入"
                        clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="info-prop"
                 v-if="formType == 'detail'">
              <span class="info-title-2">备注: </span>
              <span>{{ formData.remark || "--" }}</span>
            </div>
            <el-form-item :label-width="labelWidth"
                          label="备注"
                          class="wd-wr"
                          v-else>
              <el-input v-model="formData.remark"
                        placeholder="请输入"
                        clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <div class="info-prop"
                 v-if="formType == 'detail'">
              <span class="info-title-2">特扶类别: </span>
              <span>{{ specialSupportTypeName(formData.specialSupportType) }}</span>
            </div>
            <el-form-item :label-width="labelWidth"
                          label="特扶类别"
                          v-else>
              <el-select v-model="formData.specialSupportType"
                         clearable>
                <el-option v-for="item in specialSupportTypeList"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-col v-if="formData.specialSupportType==='2'"
                  :span="12">
            <div class="info-prop"
                 v-if="formType == 'detail'">
              <span class="info-title-2">子女姓名: </span>
              <span>{{  formData.childName||'--' }}</span>
            </div>
            <el-form-item :label-width="labelWidth"
                          label="子女姓名"
                          v-else>
              <el-input v-model="formData.childName"
                        placeholder="请输入"
                        clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col v-if="formData.specialSupportType"
                  :span="12">
            <div class="info-prop"
                 v-if="formType == 'detail'">
              <span class="info-title-2">子女性别: </span>
              <span>{{
                formData.childGender
                  ? formData.childGender == "1"
                    ? "男"
                    : formData.childGender == "2"
                    ? "女"
                    : "--"
                  : "--"
              }}</span>
            </div>
            <el-form-item :label-width="labelWidth"
                          label="子女性别"
                          v-else>
              <el-select v-model="formData.childGender"
                         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-col>
          <el-col v-if="formData.specialSupportType==='1'"
                  :span="12">
            <div class="info-prop"
                 v-if="formType == 'detail'">
              <span class="info-title-2">子女死亡日期: </span>
              <span>{{  formData.childDeathDate||'' }}</span>
            </div>
            <el-form-item :label-width="labelWidth"
                          label="子女死亡日期"
                          v-else>
              <el-date-picker v-model="formData.childDeathDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择日期"
                              style="width: 202px"
                              clearable>
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-if="formData.specialSupportType==='2'">
          <el-col :span="12">
            <div class="info-prop"
                 v-if="formType == 'detail'">
              <span class="info-title-2">伤残类别: </span>
              <span>{{ childDisabilityCategoryCodeName(formData.childDisabilityCategoryCode) }}</span>
            </div>
            <el-form-item :label-width="labelWidth"
                          label="伤残类别"
                          v-else>
              <el-select v-model="formData.childDisabilityCategoryCode"
                         clearable>
                <el-option v-for="item in dicts.childDisabilityCategoryCodeList"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <div class="info-prop"
                 v-if="formType == 'detail'">
              <span class="info-title-2">伤残等级: </span>
              <span>{{ childDisabilityLevelName(formData.childDisabilityLevel) }}</span>
            </div>
            <el-form-item :label-width="labelWidth"
                          label="伤残等级"
                          v-else>
              <el-select v-model="formData.childDisabilityLevel"
                         clearable>
                <el-option v-for="item in dicts.childDisabilityLevelList"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
    </div>
    <div class="div_btn">
      <el-button size="small"
                 @click="handleCancle">取 消</el-button>
      <el-button v-if="formType!='detail'"
                 size="small"
                 type="primary"
                 :disabled="btnDisable"
                 @click="handleComfirm">确 定</el-button>
    </div>
  </div>
</template>
      
        <script>
import { Loading } from "element-ui"; // 引入Loading服务
import { requestPost, requestGet } from "@/js/dai/request";
import nextTick from "dai-js/tools/nextTick";
import { genderList, binaryOptionList, idTypeList } from "@/js/columns/constants";
import { isCard } from "@/utils/validate";

let loading; // 加载动画

export default {
  props: {
    formType: {
      type: String,
      default: 'add'
    },
    source: {
      //展示来源：manage  管理平台    visiual  可视化平台
      type: String,
      default: "manage",
    },
  },

  data () {
    return {
      btnDisable: false,
      optionsA: [],
      labelWidth: '120px',

      formData: {
        agencyId: '',
        name: "",
        mobile: "",
        idType: "",
        idNum: "",
        birthday: "",
        gender: null,
        nation: "",
        localResidenceFlag: null,
        placeOfDomicile: "",//户籍地址
        currentResidence: "",//现居地址
        marriage: '',//婚姻状况
        bankAccount: '', //银行卡号
        specialSupportType: '',//特扶类别
        childName: '',//子女姓名
        childGender: '',//子女性别
        childDeathDate: '',//子女死亡日期
        childDisabilityCategoryCode: '',//伤残类别
        childDisabilityLevel: '',//伤残等级
        remark: '',     //备注   


        // agencyId: "1582261714844827649",
        // bankAccount: "33333",
        // birthday: "2023-08-08 00:00:00",
        // currentResidence: "现居地址",
        // gender: "1",
        // idNum: "211103199101010000",
        // idType: 1,
        // localResidenceFlag: 1,
        // marriage: "weihun",
        // mobile: "15111111111",

        // nation: "1",
        // placeOfDomicile: "户籍地址",
        // remark: "备注",

        // specialSupportType: "1",
        // name: "失独",
        // childGender: "1",
        // childDeathDate: "2023-08-24",

        // specialSupportType: "2",
        // name: "伤残",
        // childName: "子女姓名",
        // childGender: "1",
        // childDisabilityCategoryCode: "",
        // childDisabilityLevel: "",


      },

      genderList,
      binaryOptionList,
      idTypeList,


      scopeId: "",

      specialSupportTypeList: [
        {
          value: '1',
          label: '失独'
        },
        {
          value: '2',
          label: '伤残'
        }
      ],

      dicts: {
        nationList: [],
        childDisabilityCategoryCodeList: [],
        childDisabilityLevelList: [],
        marriageList: [],

      },
    };
  },
  computed: {
    dataRule () {
      let checkIdCard = (rule, value, callback) => {
        if (value === "") {
          callback(new Error("请输入证件号"));
        } else {
          if (!isCard(value)) {
            callback(new Error("请输入正确的证件号"));
          }
          callback();
        }
      };
      return {
        agencyId: [{ required: true, message: "所属组织不能为空", trigger: "bulr" }],
        name: [{ required: true, message: "姓名不能为空", trigger: "bulr" }],
        idNum: [
          { required: true, message: "证件号不能为空", trigger: "bulr" },
          { required: true, validator: checkIdCard, trigger: "blur" },
        ],
        idType: [{ required: true, message: "证件类型不能为空", trigger: "bulr" },],
        childName: [{ required: true, message: "子女姓名不能为空", trigger: "bulr" },],
      }

    },
  },

  watch: {},

  components: {},
  async created () {
    await this.getDicts();
    await this.getGridList();
  },
  async mounted () {
    this.startLoading();
    await this.endLoading();
  },

  methods: {
    async initForm (type, row) {
      this.formType = type;
      this.scopeId = row.categorizedResiId;
      await this.getDetail(this.scopeId);
    },
    async getDetail (categorizedResiId) {
      const url = `/actual/base/resiCategorized/specialSupport/detail/${categorizedResiId}`;
      const { data, code, msg } = await requestGet(url);
      if (code === 0) {
        this.formData = { ...data };
      } else {
        this.$message.error(msg);
      }
    },
    handleChangeAngency (val) {

      let obj = this.$refs["ref_cascader_agency"].getCheckedNodes()[0].data;
      console.log('改变组织', obj)
      if (obj) {
        if (obj.level !== 'community') {
          this.$message.info('请选择社区')
          this.formData.agencyId = ''
          return false
        } else {
          this.formData.agencyId = val
        }
      }
    },
    async handleComfirm () {
      this.$refs["ref_add_form"].validate(async (valid) => {
        if (!valid) {
          return false;
        }
        const url =
          this.formType === "edit"
            ? "/actual/base/resiCategorized/specialSupport/update"
            : "/actual/base/resiCategorized/specialSupport/create";
        // console.log(this.formData)
        // return false
        const { data, code, msg } = await requestPost(url, this.formData);
        if (code === 0) {
          this.$message.success(this.formType == 'add' ? "添加成功" : '修改成功');
          this.resetData();
          this.$emit("handleComfirm");
        } else if (code >= 8000) {
          this.$message.error(msg);
        }
      });
    },
    async getDicts () {
      try {
        const requests = [
          this.$http.post("sys/dict/data/nation", {
            formCode: "resi_base_info",
          }),

          this.$http.post('sys/dict/data/dictlist', {
            'dictType': 'disability_category_code'
          }),
          this.$http.post('sys/dict/data/dictlist', {
            'dictType': 'disability_level'
          }),
          this.$http.post("sys/dict/data/dictlist", {
            dictType: "marriage"
          }),

        ];
        const dictKeys = [
          "nationList",
          "childDisabilityCategoryCodeList",
          "childDisabilityLevelList",
          "marriageList",

        ]; // 对应的键名

        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);
      }
    },
    nationName (val) {
      let filtered = this.dicts.nationList.filter(
        (item) => item.value == val
      );
      let str = filtered.length > 0 ? filtered[0].label : null;
      return str ? str : "--";
    },
    marriageName (val) {
      let filtered = this.dicts.marriageList.filter(
        (item) => item.value == val
      );
      let str = filtered.length > 0 ? filtered[0].label : null;
      return str ? str : "--";
    },
    idTypeName (val) {
      let filtered = this.idTypeList.filter(
        (item) => item.value == val
      );
      let str = filtered.length > 0 ? filtered[0].label : null;
      return str ? str : "--";
    },
    specialSupportTypeName (val) {
      let filtered = this.specialSupportTypeList.filter(
        (item) => item.value == val
      );
      let str = filtered.length > 0 ? filtered[0].label : null;
      return str ? str : "--";
    },
    childDisabilityLevelName (val) {
      let filtered = this.dicts.childDisabilityLevelList.filter(
        (item) => item.value == val
      );
      let str = filtered.length > 0 ? filtered[0].label : null;
      return str ? str : "--";
    },
    childDisabilityCategoryCodeName (val) {
      let filtered = this.dicts.childDisabilityCategoryCodeList.filter(
        (item) => item.value == val
      );
      let str = filtered.length > 0 ? filtered[0].label : null;
      return str ? str : "--";
    },
    getGridList () {
      const { user } = this.$store.state
      this.dataListLoading = true
      const params = {
        agencyId: user.agencyId,
        client: 'gov'
      }
      this.$http
        // .post('/gov/org/userhouse/service/serviceScopeTree')
        // .post('/data/aggregator/org/agencytree', params)
        .post('/gov/org/customeragency/staffinagencylist')
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          } else {

            let { agencyList, subAgencyList } = res.data

            const _arr = [{ ...agencyList, subAgencyList: [...subAgencyList] }]
            this.optionsA = this.deepTree(_arr)
          }
        })
        .catch(() => {
          this.dataListLoading = false
          return this.$message.error('网络错误')
        })
      this.dataListLoading = false
    },
    deepTree (arr) {
      if (Array.isArray(arr)) {
        return arr.map(item => {
          return {
            ...item,
            subAgencyList: item.subAgencyList.length > 0 && this.deepTree(item.subAgencyList) || null
          }
        })
      }
    },
    handleCancle () {
      this.resetData();
      this.$emit("handleClose");
    },

    resetData () {
      this.formData = {};
    },
    // 开启加载动画
    startLoading () {
      loading = Loading.service({
        lock: true, // 是否锁定
        text: "正在加载……", // 加载中需要显示的文字
        background: "rgba(0,0,0,.7)", // 背景颜色
      });
    },
    // 结束加载动画
    endLoading () {
      if (loading) {
        loading.close();
      }
    },
  },
};
  </script>
      
        <style lang="scss" scoped>
@import "@/assets/scss/modules/management/form-main.scss";
@import "@/assets/scss/modules/visual/a_customize.scss";
@import "@/assets/scss/modules/management/detail-main.scss";

.form-item::v-deep .el-form-item__label {
  color: #fff;
}
.form-item {
  .el-radio {
    color: #fff;
  }
  .el-checkbox {
    color: #fff;
  }
}

.wd-wr {
  width: 100%;
  /deep/ .el-form-item__content {
    width: calc(100% - 148px);
  }
}
.info-prop {
  margin-top: 29px;
  .info-title-2 {
    width: 100px;
    text-align: right;
    display: inline-block;
    padding-right: 10px;
  }
}
.width-two {
  width: 553px;
}
</style>
      
    
    