<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="100px" prop="agencyId">
              <el-cascader v-if="formType == 'add'" ref="ref_cascader_agency" class="width-two" v-model="selGridId"
                :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="100px" 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="100px" 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>{{ formData.idTypeName || "--" }}</span>
            </div>
            <el-form-item label-width="100px" label="证件类型" prop="idType" v-else>
              <el-select v-model="formData.idType" clearable>
                <el-option v-for="item in dicts.idCard_type" :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="100px" 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="100px" 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="100px" 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>{{ formData.nationName || "--" }}</span>
            </div>
            <el-form-item label-width="100px" 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.localResidenceFlag == 0
                    ? "否"
                    : "--"
                : "--"
              }}</span>
            </div>
            <el-form-item label-width="100px" 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="100px" 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="100px" 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>{{ formData.cultureLevelName || "--" }}</span>
            </div>
            <el-form-item label-width="100px" label="文化程度" v-else>
              <el-select v-model="formData.cultureLevel" clearable>
                <el-option v-for="item in dicts.educationList" :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.disabilityFlag != null
                ? formData.disabilityFlag == 0
                  ? "健康"
                  : formData.disabilityFlag == 1
                    ? "伤残"
                    : "--"
                : "--"
              }}</span>
            </div>
            <el-form-item label-width="100px" label="是否残疾" v-else>
              <el-select v-model="formData.disabilityFlag" clearable>
                <el-option v-for="item in disabilityFlagList" :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="formData.disabilityFlag == 1">
          <el-col :span="12">
            <div class="info-prop" v-if="formType == 'detail'">
              <span class="info-title-2">残疾类别: </span>
              <span>{{ formData.disabilityCategoryName || "--" }}</span>
            </div>
            <el-form-item label-width="100px" label="残疾类别" v-else>
              <el-select v-model="formData.disabilityCategoryCode" clearable>
                <el-option v-for="item in dicts.disability_category_code" :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.disabilityLevelName || "--" }}</span>
            </div>
            <el-form-item label-width="100px" label="伤残等级" v-else>
              <el-select v-model="formData.disabilityLevel" clearable>
                <el-option v-for="item in dicts.disability_level" :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>{{ formData.originWorkUnit || "--" }}</span>
            </div>
            <el-form-item label-width="100px" label="原工作单位" v-else>
              <el-input v-model="formData.originWorkUnit" placeholder="请输入" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12"> </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.unemploymentTime || "--" }}</span>
            </div>
            <el-form-item label-width="100px" label="失业时间" v-else>
              <el-date-picker v-model="formData.unemploymentTime" type="date" value-format="yyyy-MM-dd" 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.unemploymentNum || "--" }}</span>
            </div>
            <el-form-item label-width="100px" label="失业证号" v-else>
              <el-input v-model="formData.unemploymentNum" 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.unemploymentReasonName || "--" }}</span>
            </div>
            <el-form-item label-width="100px" label="失业原因" v-else>
              <el-select v-model="formData.unemploymentReason" clearable>
                <el-option v-for="item in dicts.unemployment_cause" :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.employmentNum || "--" }}</span>
            </div>
            <el-form-item label-width="100px" label="再就业优惠证号" v-else>
              <el-input v-model="formData.employmentNum" 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.specialSkill || "--" }}</span>
            </div>
            <el-form-item label-width="100px" label="技术特长" v-else>
              <el-input v-model="formData.specialSkill" 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.unempCompensationFlag != null
                ? formData.unempCompensationFlag == 0
                  ? "否"
                  : formData.unempCompensationFlag == 1
                    ? "是"
                    : "--"
                : "--"
              }}</span>
            </div>
            <el-form-item label-width="100px" label="是否领取失业金" v-else>
              <el-select v-model="formData.unempCompensationFlag" 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="12">
            <div class="info-prop" v-if="formType == 'detail'">
              <span class="info-title-2">是否就业困难对象: </span>
              <span>{{
                formData.employmentHardFlag!=null
                ? formData.employmentHardFlag == 1
                  ? "是"
                  : formData.employmentHardFlag == 0
                    ? "否"
                    : "--"
                : "--"
              }}</span>
            </div>
            <el-form-item label-width="100px" label="是否就业困难对象" v-else>
              <el-select v-model="formData.employmentHardFlag" 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-col :span="12">
            <div class="info-prop" v-if="formType == 'detail'">
              <span class="info-title-2">劳动能力就业愿景: </span>
              <span>{{ formData.employmentWishName || "--" }}</span>
            </div>
            <el-form-item label-width="100px" label="劳动能力就业愿景" v-else>
              <el-select v-model="formData.employmentWish" clearable>
                <el-option v-for="item in dicts.career_goals" :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.remark || "--" }}</span>
            </div>
            <el-form-item label-width="100px" label="备注" class="wd-wr" v-else>
              <el-input v-model="formData.remark" placeholder="请输入" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="div_btn">
      <el-button size="small" @click="handleCancle">取 消</el-button>
      <el-button 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,
  disabilityFlagList,
} from "@/js/columns/constants";

let loading; // 加载动画

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

  data() {
    return {
      btnDisable: false,
      selGridId: [],
      optionsA: [],

      genderList,
      binaryOptionList,
      disabilityFlagList,

      formData: {
        name: "",
        mobile: "",
        idType: "",
        idNum: "",
        birthday: "",
        gender: null,
        nation: "",
        localResidenceFlag: null,
        placeOfDomicile: "",
        currentResidence: "",
        cultureLevel: "",
        disabilityFlag: null,
        originWorkUnit: "",
        disabilityCategoryCode: "",
        disabilityLevel: "",
        unemploymentTime: "",
        unemploymentNum: "",
        unemploymentReason: "",
        employmentNum: "",
        unempCompensationFlag: null,
        employmentHardFlag: null,
        employmentWish: "",
        specialSkill: "",
        remark: "",
        agencyId: ""
      },

      dataRule: {
        name: [{ required: true, message: "姓名不能为空", trigger: "bulr" }],
        idNum: [{ required: true, message: "证件号不能为空", trigger: "bulr" }],

        idType: [
          { required: true, message: "证件类型不能为空", trigger: "bulr" },
        ],
        agencyId: [{ required: true, message: "所属组织不能为空", trigger: "bulr" }],
      },
      scopeId: "",

      dicts: {
        nationList: [],
        educationList: [],
        idCard_type: [],
        disability_category_code: [],
        disability_level: [],
        unemployment_cause: [],
        career_goals: [],
      },
    };
  },

  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/unemployed/detail/${categorizedResiId}`;
      const { data, code, msg } = await requestGet(url);
      if (code === 0) {
        console.log(data);
        this.formData = { ...data };
        this.formData.idType = this.formData.idType.toString()
      } else {
        this.$message.error(msg);
      }
    },
    async handleComfirm() {
      this.$refs["ref_add_form"].validate(async (valid) => {
        if (!valid) {
          return false;
        }
        if (this.formType == 'edit') {
          this.formData.categorizedResiId = this.scopeId
        }
        const url =
          this.formType === "edit"
            ? "/actual/base/resiCategorized/unemployed/update"
            : this.formType == 'add' ? "/actual/base/resiCategorized/unemployed/create" : '';
        if (url) {
          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);
          }
        } else {
          this.$emit("handleComfirm", this.formType);
        }

      });
    },
    async getDicts() {
      try {
        const requests = [
          this.$http.post("sys/dict/data/nation", {
            formCode: "resi_base_info",
          }),
          this.$http.post("sys/dict/data/education", {
            formCode: "resi_base_info",
          }),
          this.$http.post("sys/dict/data/dictlist", {
            dictType: "idCard_type",
          }),
          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: "unemployment_cause",
          }),
          this.$http.post("sys/dict/data/dictlist", {
            dictType: "career_goals",
          }),
        ];
        const dictKeys = [
          "nationList",
          "educationList",
          "idCard_type",
          "disability_category_code",
          "disability_level",
          "unemployment_cause",
          "career_goals",
        ]; // 对应的键名

        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);
      }
    },
    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();
      }
    },
    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 = ''
          this.selGridId = []
          return false
        } else {
          this.formData.agencyId = val
        }
      }
    },
    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
          }
        })
      }
    },
  },
};
</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>
