<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1080">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <div class="form_title">基本信息</div>
      <el-row>
        <el-col :span="12">
          <el-form-item label="方案名称" prop="schemeName">
            <el-input v-model="formData.schemeName" placeholder="请输入方案名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="参保城市" prop="city">
            <el-cascader
              v-model="formData.city"
              :options="areaList"
              :props="{
                children: 'children',
                label: 'name',
                value: 'name',
                emitPath: true
              }"
              @change="cityChange"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="可选参保方案" prop="houseType">
            <el-select
              v-model="formData.houseType"
              placeholder="请选择"
              style="width: 100%"
              @change="houseTypeChange"
            >
              <el-option
                v-for="(item, index) in typeList"
                :key="index"
                :label="item.InsuredType"
                :value="item.AccountNo"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-radio-group
        v-model="formData.schemeType"
        style="margin-left: 20px; marigin-top: 10px"
        @change="tabChange"
      >
        <el-radio-button
          v-for="dict in getIntDictOptions(DICT_TYPE.HR_SCHEME_TYPE)"
          :key="dict.value"
          :value="dict.value"
          >{{ dict.label }}</el-radio-button
        >
      </el-radio-group>
    </el-form>
    <el-form ref="otherFormRef" :model="otherForm">
      <div class="form_title">社保</div>
      <el-table
        :data="otherForm.topList"
        class="my-table"
        :summary-method="getSummaries"
        show-summary
        border
        stripe
      >
        <el-table-column
          :min-width="150"
          fixed
          prop="projectName"
          label="项目名称"
          show-overflow-tooltip
        >
          <template #default="scope">
            <el-form-item
              v-if="scope.row.type == 9 || scope.row.type == 11"
              :prop="`topList[${scope.$index}].projectName`"
              :rules="{ required: true, message: '请输入', trigger: 'change' }"
              label=""
            >
              <el-input v-model="scope.row.projectName" placeholder="请输入" type="text" />
            </el-form-item>
            {{ getProjectName(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column
          v-for="(item, index) in tableFields"
          :key="index"
          :prop="item.prop"
          :label="item.label"
          :min-width="150"
          show-overflow-tooltip
        >
          <template #default="scope">
            <el-form-item
              :prop="`topList[${scope.$index}][${scope.column.property}]`"
              :rules="{ required: true, message: '请输入', trigger: 'change' }"
              label=""
            >
              <el-input
                v-model="scope.row[scope.column.property]"
                v-wk-number="getNumberType(scope.column.property)"
                :disabled="getLeftInputDisabledValue(scope.column.property)"
                placeholder="请输入"
                type="text"
                @input="numberInputChange(scope.row)"
              >
                <template v-if="getLeftInputAppendShowValue(scope.column.property)" #append
                  >%</template
                >
              </el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <!--        <el-table-column label="操作" fixed="right" width="100">-->
        <!--          <template #default="scope">-->
        <!--            <el-button type="danger" link @click="deleteItems(scope.$index, 'topList')"-->
        <!--              >删除</el-button-->
        <!--            >-->
        <!--          </template>-->
        <!--        </el-table-column>-->
      </el-table>
      <div class="form_title">公积金</div>
      <el-table
        :data="otherForm.bottomList"
        stripe
        :summary-method="getSummaries"
        show-summary
        style="width: 100%"
      >
        <el-table-column
          :min-width="150"
          fixed
          prop="projectName"
          label="项目名称"
          show-overflow-tooltip
        >
          <template #default="scope">
            <el-form-item
              v-if="scope.row.type == 9 || scope.row.type == 11"
              :prop="`bottomList[${scope.$index}].projectName`"
              :rules="{ required: true, message: '请输入', trigger: 'change' }"
              label=""
            >
              <el-input v-model="scope.row.projectName" placeholder="请输入" type="text" />
            </el-form-item>
            {{ getProjectName(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column
          v-for="(item, index) in tableFields"
          :key="index"
          :prop="item.prop"
          :label="item.label"
          :min-width="150"
          show-overflow-tooltip
        >
          <template #default="scope">
            <el-form-item
              :prop="`bottomList[${scope.$index}][${scope.column.property}]`"
              :rules="{ required: true, message: '请输入', trigger: 'change' }"
              label=""
            >
              <el-input
                v-model="scope.row[scope.column.property]"
                v-wk-number="getNumberType(scope.column.property)"
                :disabled="getLeftInputDisabledValue(scope.column.property)"
                placeholder="请输入"
                type="text"
                @input="numberInputChange(scope.row)"
              >
                <template v-if="getLeftInputAppendShowValue(scope.column.property)" #append
                  >%</template
                >
              </el-input>
            </el-form-item>
          </template>
        </el-table-column>
        <!--        <el-table-column label="操作" fixed="right" width="100">-->
        <!--          <template #default="scope">-->
        <!--            <el-button type="danger" link @click="deleteItems(scope.$index, 'bottomList')"-->
        <!--              >删除</el-button-->
        <!--            >-->
        <!--          </template>-->
        <!--        </el-table-column>-->
      </el-table>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { InsuranceSchemeApi, InsuranceScheme } from '@/api/hr/insurancescheme'
import { defaultProps } from '@/utils/tree'
import { getAreaTree } from '@/api/system/area'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { isEmpty, floatAdd } from '@/utils'
import { ElMessageBox } from 'element-plus'
/** 社保方案 表单 */
defineOptions({ name: 'InsuranceSchemeForm' })
const providentFundTypeValue = {
  1: '养老保险',
  2: '医疗保险',
  3: '失业保险',
  4: '工伤保险',
  5: '生育保险',
  6: '补充大病医疗保险',
  7: '补充养老保险',
  8: '残保险'
  // 9: '社保自定义'
}
const socialSecurityTypeValue = {
  10: '公积金'
  // 11: '公积金自定义'
}
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const schemeTypeList = getIntDictOptions(DICT_TYPE.HR_SCHEME_TYPE)
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const areaList = ref() // 区域树
const formData = ref({
  schemeId: undefined,
  schemeName: undefined,
  city: undefined,
  houseType: undefined,
  schemeType: schemeTypeList[0].value
})
const formRules = reactive({
  schemeName: [{ required: true, message: '方案名称不能为空', trigger: 'blur' }],
  city: [{ required: true, message: '参保城市不能为空', trigger: 'blur' }],
  schemeType: [{ required: true, message: '参保类型 1 比例 2 金额不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref
const otherFormRef = ref()
const otherForm = ref({
  topList: [],
  bottomList: [],
  leftList: [],
  leftFundList: [],
  rightList: [],
  rightFundList: []
})
const objDeepCopy = (source) => {
  if (typeof source === 'object') {
    var sourceCopy = source instanceof Array ? [] : {}
    for (var item in source) {
      if (!source[item]) {
        sourceCopy[item] = source[item]
      } else {
        sourceCopy[item] =
          typeof source[item] === 'object' ? objDeepCopy(source[item]) : source[item]
      }
    }
    return sourceCopy
  }
  return source
}
let schemeId = ''
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    schemeId = id
    formLoading.value = true
    try {
      const res = await InsuranceSchemeApi.queryInsuranceSchemeById(id)
      res.city = res.city.split('/')
      formData.value = res
      otherForm.value = {
        topList: res.socialSecurityProjectList,
        bottomList: res.providentFundProjectList,
        leftList: [],
        leftFundList: [],
        rightList: [],
        rightFundList: []
      }
    } finally {
      formLoading.value = false
    }
  } else {
    otherForm.value = {
      topList: getDefaultItems([1, 2, 3, 4, 5]),
      bottomList: getDefaultItems([10]),
      leftList: [],
      leftFundList: [],
      rightList: [],
      rightFundList: []
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  await otherFormRef.value.validate()
  if (otherForm.value.topList.length == 0) {
    message.error('请添加社保项目')
    return
  }
  const params = {
    schemeType: formData.value.schemeType,
    schemeName: formData.value.schemeName,
    houseType: formData.value.houseType
  }
  if (schemeId) {
    params.schemeId = schemeId
  }
  if (formData.value.city && formData.value.city.length > 0) {
    let address = formData.value.city.join('/')
    params.city = address
  } else {
    params.city = ''
  }
  params.socialSecurityProjectList = otherForm.value.topList
  params.providentFundProjectList = otherForm.value.bottomList
  ElMessageBox.confirm('编辑参保方案后，不会变更现有的参保信息，确定提交？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      // 提交请求
      formLoading.value = true
      try {
        await InsuranceSchemeApi.addInsuranceScheme(params)
        message.success('操作成功')
        dialogVisible.value = false
        // 发送操作成功的事件
        emit('success')
      } finally {
        formLoading.value = false
      }
    })
    .catch(() => {})
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    schemeId: undefined,
    schemeName: undefined,
    city: undefined,
    houseType: undefined,
    schemeType: schemeTypeList[0].value
  }
  formRef.value?.resetFields()
}
const typeList = ref([{ InsuredType: '社保', AccountNo: 'SS100073' }])
/** 参保类型改变 */
const changeSchemeType = (schemeType: number) => {}
const getSchemeType = (city) => {
  InsuranceSchemeApi.queryInsuranceType({
    cityId: city
  })
    .then((res) => {
      const data = res.data || []
      typeList.value = data.map((item) => {
        return {
          label: item.InsuredType,
          value: item.AccountNo
        }
      })
    })
    .catch(() => {})
}
const cityChange = (val) => {
  console.log(val)
  console.log(formData.value.city)
}
const tableFields = computed(() => {
  if (formData.value.schemeType == 1) {
    return [
      {
        label: '默认基数',
        prop: 'defaultAmount'
      },
      {
        label: '公司缴纳比例',
        prop: 'corporateProportion'
      },
      {
        label: '个人缴纳比例',
        prop: 'personalProportion'
      },
      {
        label: '公司金额',
        prop: 'corporateAmount'
      },
      {
        label: '个人金额',
        prop: 'personalAmount'
      }
    ]
  }
  return [
    {
      label: '默认基数',
      prop: 'defaultAmount'
    },
    {
      label: '公司金额',
      prop: 'corporateAmount'
    },
    {
      label: '个人金额',
      prop: 'personalAmount'
    }
  ]
})
const getDefaultItems = (list) => {
  return list.map((type) => getDefaultItem(type))
}
const typeDetail = ref(null)
const getDefaultItem = (type) => {
  const typeValue = typeDetail.value ? typeDetail.value[type] : null
  return {
    type: type || 1,
    projectName: '',
    corporateAmount: typeValue ? typeValue.corporateAmount : 0,
    corporateProportion: typeValue ? typeValue.corporateProportion : 0,
    defaultAmount: typeValue ? typeValue.defaultAmount : 0,
    personalAmount: typeValue ? typeValue.personalAmount : 0,
    personalProportion: typeValue ? typeValue.personalProportion : 0
  }
}
const getProjectName = (type) => {
  if (type < 9) {
    return providentFundTypeValue[type]
  }
  return socialSecurityTypeValue[type]
}
const getNumberType = (prop) => {
  if (['corporateAmount', 'personalAmount', 'defaultAmount'].includes(prop)) {
    return 'positive3Float'
  } else if (['corporateProportion', 'personalProportion'].includes(prop)) {
    return 'positive4Float'
  }

  return ''
}
/**
 * 左边表格是否不能输入
 */
const getLeftInputDisabledValue = (prop) => {
  return formData.value.schemeType == 2
    ? false
    : ['corporateAmount', 'personalAmount'].includes(prop)
}
const numberInputChange = (data) => {
  if (formData.value.schemeType == 1) {
    const personalProportion = parseFloat(data.personalProportion || 0)
    const personalAmount =
      parseFloat(data.defaultAmount || 0) * (personalProportion > 0 ? personalProportion / 100 : 0)
    data.personalAmount = Math.round(personalAmount * 100) / 100
    const corporateProportion = parseFloat(data.corporateProportion || 0)
    const corporateAmount =
      parseFloat(data.defaultAmount || 0) *
      (corporateProportion > 0 ? corporateProportion / 100 : 0)
    data.corporateAmount = Math.round(corporateAmount * 100) / 100
  }
}
/**
 * 左边表格是否展示百分号
 */
const getLeftInputAppendShowValue = (prop) => {
  return ['corporateProportion', 'personalProportion'].includes(prop)
}
const deleteItems = (index, key) => {
  console.log(index, key, otherForm.value[key])
  otherForm.value[key].splice(index, 1)
}
const tabChange = () => {
  if (formData.value.schemeType == 1) {
    otherForm.value.rightList = otherForm.value.topList
    otherForm.value.rightFundList = otherForm.value.bottomList

    otherForm.value.topList =
      otherForm.value.leftList.length == 0
        ? getDefaultItems([1, 2, 3, 4, 5])
        : objDeepCopy(otherForm.value.leftList)
    otherForm.value.bottomList =
      otherForm.value.leftFundList.length == 0
        ? getDefaultItems([10])
        : objDeepCopy(otherForm.value.leftFundList)
  } else {
    otherForm.value.leftList = otherForm.value.topList
    otherForm.value.leftFundList = otherForm.value.bottomList

    otherForm.value.topList =
      otherForm.value.rightList.length == 0
        ? getDefaultItems([1, 2, 3, 4, 5])
        : objDeepCopy(otherForm.value.rightList)
    otherForm.value.bottomList =
      otherForm.value.rightFundList.length == 0
        ? getDefaultItems([10])
        : objDeepCopy(otherForm.value.rightFundList)
  }
}
const getSummaries = (param) => {
  const { columns, data } = param
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '总计'
      return
    } else if (
      ['personalProportion', 'corporateProportion', 'defaultAmount'].includes(column.property) ||
      !column.property
    ) {
      sums[index] = ''
      return
    }
    const values = data.map((item) => Number(item[column.property]))
    if (!values.every((value) => isNaN(value))) {
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!isNaN(value)) {
          return floatAdd(prev, curr)
        } else {
          return prev
        }
      }, 0)
    } else {
      sums[index] = 'N/A'
    }
  })
  return sums
}
const handleotherForm = (detail) => {
  if (detail) {
    otherForm.value.topList.forEach((item) => {
      const typeValue = detail[item.type]
      if (typeValue) {
        item.corporateAmount = typeValue.corporateAmount
        item.corporateProportion = typeValue.corporateProportion
        item.defaultAmount = typeValue.defaultAmount
        item.personalAmount = typeValue.personalAmount
        item.personalProportion = typeValue.personalProportion
      } else {
        handleItemDefault(item)
      }
    })

    otherForm.value.bottomList.forEach((item) => {
      const typeValue = detail[item.type]
      if (typeValue) {
        item.corporateAmount = typeValue.corporateAmount
        item.corporateProportion = typeValue.corporateProportion
        item.defaultAmount = typeValue.defaultAmount
        item.personalAmount = typeValue.personalAmount
        item.personalProportion = typeValue.personalProportion
      } else {
        handleItemDefault(item)
      }
    })
  } else {
    otherForm.value.topList.forEach((item) => {
      handleItemDefault(item)
    })

    otherForm.value.bottomList.forEach((item) => {
      handleItemDefault(item)
    })
  }

  otherForm.value.leftList = []
  otherForm.value.leftFundList = []
  otherForm.value.rightList = []
  otherForm.value.rightFundList = []
}
const handleItemDefault = (item) => {
  item.corporateAmount = 0
  item.corporateProportion = 0
  item.defaultAmount = 0
  item.personalAmount = 0
  item.personalProportion = 0
}
const houseTypeChange = (val) => {
  if (val) {
    getSchemeTypeDetail(val)
  }
}
const getSchemeTypeDetail = (val) => {}
/** 初始化 **/
onMounted(async () => {
  areaList.value = await getAreaTree()
})
</script>
<style>
.form_title {
  padding-left: 10px;
  margin-top: 8px;
  margin-bottom: 10px;
  font-size: 14px;
  border-left: 4px solid #409eff;
}

.my-table {
  margin-top: 20px;
}
</style>
