<template>
  <div class="container2">
    <a-row>
      <a-col :span="24" style="padding-top: 10px;padding-left: 30px;padding-right: 30px;">
        <a-table :dataSource="filteredTableData" :columns="columns" :pagination="false" bordered size="small"
          :rowClassName="setRowClassName">
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'd1'">
              <span>{{ applyObj[record.d1] }}</span>
            </template>
            <template v-if="column.dataIndex === 'd2' && isImg(record.d1)">
              <JImageUpload :fileMax="1" v-model:value="record.d2" disabled></JImageUpload>
            </template>
            <template v-if="column.dataIndex === 'd3' && isImg(record.d1)">
              <JImageUpload :fileMax="1" v-model:value="record.d3" disabled></JImageUpload>
            </template>
            <template
              v-if="column.dataIndex === 'd2' && (record.d1 == 'orgProvince' || record.d1 == 'orgCity' || record.d1 == 'orgDistrict')">
              <span>{{ provinceOptions[record.d2] }}</span>
            </template>
            <template
              v-if="column.dataIndex === 'd3' && (record.d1 == 'orgProvince' || record.d1 == 'orgCity' || record.d1 == 'orgDistrict')">
              <span>{{ provinceOptions[record.d3] }}</span>
            </template>
            <template v-if="column.dataIndex === 'd2' && record.d1 == 'orgBuildingArea'">
              <span>{{ record.d2 }}㎡</span>
            </template>
            <template v-if="column.dataIndex === 'd3' && record.d1 == 'orgBuildingArea'">
              <span>{{ record.d3 }}㎡</span>
            </template>
            <template v-if="column.dataIndex === 'd2' && record.d1 == 'endTime'">
              <span>{{ record.d2 == '9999-12-31' ? '长期' : record.d2 }}</span>
            </template>
            <template v-if="column.dataIndex === 'd3' && record.d1 == 'endTime'">
              <span>{{ record.d3 == '9999-12-31' ? '长期' : record.d3 }}</span>
            </template>
          </template>
        </a-table>
      </a-col>
    </a-row>
    <a-form style="margin-top: 14px;height: 100px;" ref="formRef" layout="horizontal" :model="formData" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="审核结果" name="status" v-bind="validateInfos.status">
            <a-select v-model:value="formData.status" style="width: 200px" placeholder="请选择审核结果">
              <a-select-option value="modifyPass">审核通过</a-select-option>
              <a-select-option value="modifyFail">审核驳回</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span="12" v-if="formData.status == 'modifyFail'">
          <a-form-item label="驳回原因" name="auditContent" v-bind="validateInfos.auditContent">
            <a-textarea :maxlength="50" show-count v-model:value="formData.auditContent" placeholder="请输入驳回原因（如驳回）"
              style="width: 100%" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { Table as ATable, Input, Row, Col, Form } from 'ant-design-vue';
import { applyObj } from '../ElderInfo.data'
import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
import { getModifyInfo, guaAudit } from '../ElderInfo.api'
import { useMessage } from '/@/hooks/web/useMessage';
import { initDictOptions } from '/@/utils/dict';

const formRef = ref();
const AForm = Form;
const AFormItem = Form.Item;
const useForm = Form.useForm;
const { createMessage } = useMessage();
// 表单标签布局配置
const labelCol = { span: 4 };  // 标签宽度
const wrapperCol = { span: 18 }; // 控件宽度
const isImg = (v_) => {
  return v_ == 'guardianIdCardPositive' || v_ == 'idCardNegative' || v_ == 'healthCertificatePositive' || v_ == 'bankPositive' || v_ == 'bankNegative' || v_ == 'qualification' || v_ == 'noCrimeCertificate'
}
const provinceOptions = ref({})
const formData = reactive<Record<string, any>>({
  status: undefined,
  auditContent: '',
  id: '',
  pkId: ''
});
const validatorRules = reactive({
  status: [{ required: true, message: '请选择审核结果!' },],
  auditContent: [
    {
      validator: async (_rule, value) => {
        if (formData.status === 'modifyFail' && !value) {
          return Promise.reject('请输入驳回原因!');
        }
        return Promise.resolve();
      },
    },
  ],
})
const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });
const tableData = ref([]);
const emit = defineEmits(['ok']);
// 计算属性，过滤掉不需要显示的字段
const filteredTableData = computed(() => {
  return tableData.value.filter(item =>
    item.d1 !== 'id'
    && item.d1 !== 'nuId'
    && item.d1 !== 'name'
    && item.d1 !== 'sex'
    && item.d1 !== 'age'
    && item.d1 !== 'idCard'
    && item.d1 !== 'dateOfBirth'
    && item.d1 !== 'national'
    && item.d1 !== 'houseAddress'
    && item.d1 !== 'avatarPath'
    && item.d1 !== 'medicalType'
    && item.d1 !== 'reimbType'
    && item.d1 !== 'medicalCard'
    && item.d1 !== 'educationLevel'
    && item.d1 !== 'maritalStatus'
    && item.d1 !== 'religiousBeliefs'
    && item.d1 !== 'idCardPositive'
    && item.d1 !== 'idCardNegative'
    && item.d1 !== 'accountBookHimself'
    && item.d1 !== 'frontMedical'
    && item.d1 !== 'negaticeMedical'
    && item.d1 !== 'content'
    && item.d1 !== 'currentState'
    && item.d1 !== 'guardianOpenId'
    // && item.d1 !== 'guardianName'
    // && item.d1 !== 'relationship'
    // && item.d1 !== 'guardianIdCard'
    // && item.d1 !== 'guardianPhone'
    && item.d1 !== 'guardianDateOfBirth'
    // && item.d1 !== 'guardianHomeAddress'
    // && item.d1 !== 'guardianWorkUnit'
    && item.d1 !== 'homeAddress'
    && item.d1 !== 'delFlag'
    && item.d1 !== 'createBy'
    && item.d1 !== 'createTime'
    && item.d1 !== 'updateBy'
    && item.d1 !== 'updateTime'
    && item.d1 !== 'sysOrgCode'
    && item.d1 !== 'issuingAuthority'
    && item.d1 !== 'startTime'
    && item.d1 !== 'endTime'
    && item.d1 !== 'cardIssuing'
    && item.d1 !== 'bloodType'
    && item.d1 !== 'militaryType'
    && item.d1 !== 'guardianModifyStatus'
    && item.d1 !== 'guardianModifyContent'
    && item.d1 !== 'guardianModifyId'
    && item.d1 !== 'elderModifyStatus'
    && item.d1 !== 'elderModifyContent'
    && item.d1 !== 'elderModifyId'
    && item.d1 !== 'guardianBirthDate'
    && item.d1 !== 'guardianSex'
    && item.d1 !== 'guardianNational'
    && item.d1 !== 'guardianCardHome'
  );
});

const columns = [
  {
    title: '名称',
    dataIndex: 'd1',
    key: 'd1',
    width: 150,
  },
  {
    title: '变更前',
    dataIndex: 'd2',
    key: 'd2',
  },
  {
    title: '变更后',
    dataIndex: 'd3',
    key: 'd3',
  }
];

// 设置行类名
const setRowClassName = (record) => {
  return record.d2 !== record.d3 && record.d1 !== 'createTime' ? 'highlight-row' : '';
};

async function show(record) {
  console.log("🌊 ~ show ~ record:", record)
  let data = await getModifyInfo({ id: record.id, queryModifyType: 'gua' })
  console.log("🌊 ~ show ~ data:", data)

  formData.id = record.id
  formData.guardianModifyId = record.guardianModifyId
  formData.guardianOpenId = record.guardianOpenId
  formData.name = record.name
  formData.sysOrgCode = record.sysOrgCode

  tableData.value = data.map(item => ({
    ...item,
    // 处理null/undefined显示为空字符串
    d2: item.d2 ?? '',
    d3: item.d3 ?? ''
  }));
}

async function submitForm() {
  try {
    // 触发表单验证
    await validate();
  } catch ({ errorFields }) {
    if (errorFields) {
      const firstField = errorFields[0];
      if (firstField) {
        formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
      }
    }
    return Promise.reject(errorFields);
  }
  guaAudit(formData)
    .then((res) => {
      emit('ok');
    })
}

// 初始化numberValues
onMounted(async () => {
  const dictData = await initDictOptions('sys_category,name,id,first_letter is not null order by code asc', '');
  dictData.reduce((prev, next) => {
    if (next) {
      provinceOptions.value[next['value']] = next['text'] || next['label']
    }
    return prev;
  }, []);
});

defineExpose({
  show,
  submitForm
});
</script>

<style lang="less" scoped>
.container2 {
  // padding: 16px;
}

.antd-modal-form {
  padding: 14px;
}

:deep(.ant-table-cell) {
  padding: 8px 12px !important;
}

// 高亮行样式
:deep(.highlight-row) {
  background-color: #fff1f0 !important; // 浅红色背景
}

// 表单样式调整
:deep(.ant-form-item) {
  margin-bottom: 16px;
}

:deep(.ant-table-cell-row-hover) {
  // border: 1px solid red;
}
</style>