<template>
  <div class="container2">
    <a-row>
      <a-col :span="24">
        <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 v-if="!!record.d2" :fileMax="1" :value="opeMediaAddress + record.d2" disabled>
              </JImageUpload>
              <span v-else>未上传</span>
            </template>
            <template v-if="column.dataIndex === 'd3' && isImg(record.d1)">
              <JImageUpload v-if="!!record.d3" :fileMax="1" :value="opeMediaAddress + record.d3" disabled>
              </JImageUpload>
              <span v-else>未上传</span>
            </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="applyContent" v-bind="validateInfos.applyContent">
            <a-textarea :maxlength="50" show-count v-model:value="formData.applyContent" 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 '../NuConfigSuppliersApply.data'
import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
import { getModifyInfo, auditSubmit } from '../NuConfigSuppliersApply.api';
import { useMessage } from '/@/hooks/web/useMessage';
import { initDictOptions } from '/@/utils/dict';

const opeMediaAddress = import.meta.env.VITE_OPE_MEDIA_ADDRESS
const formRef = ref();
const AForm = Form;
const AFormItem = Form.Item;
const useForm = Form.useForm;
const { createMessage } = useMessage();
// 表单标签布局配置
const labelCol = { span: 6 };  // 标签宽度
const wrapperCol = { span: 18 }; // 控件宽度
const isImg = (v_) => {
  return v_ == 'imgPath'
}
const provinceOptions = ref({})
const formData = reactive<Record<string, any>>({
  status: undefined,
  applyContent: '',
  id: '',
  pkId: '',
  openId:'',
});
const validatorRules = reactive({
  status: [{ required: true, message: '请选择审核状态!' },],
  applyContent: [
    {
      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 !== 'supplyState'
    && item.d1 !== 'wechartId'
    && item.d1 !== 'delFlag'
    && item.d1 !== 'createBy'
    && item.d1 !== 'createTime'
    && item.d1 !== 'updateBy'
    && item.d1 !== 'updateTime'
    && item.d1 !== 'sysOrgCode'
    && item.d1 !== 'izEnabled'
    && item.d1 !== 'sourceType'
  );
});

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' : '';
};

const fieldMap = {
  suppliersName: 'suppliersName',
  suppliersNature: 'suppliersNature',
  suppliersAddress: 'suppliersAddress',
  personInCharge: 'personInCharge',
  contactNumber: 'contactNumber',
  openingBank: 'openingBank',
  openingBankNo: 'openingBankNo',
  imgPath: 'imgPath',
};

async function show(record) {
  let data = await getModifyInfo({ id: record.id })

  formData.id = record.id
  formData.suppliersId = record.suppliersId
  
  // 存储id和pkId到formData
  Object.keys(fieldMap).forEach(fieldName => {
    const record = data.find(item => item.d1 === fieldName);
    if (record) {
      formData[fieldName] = record.d3;
    }
  });

  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);
  }

  if (formData.startTime) {
    formData.startTime = formData.startTime.replace(/-/g, '.');
  }
  if (formData.endTime) {
    formData.endTime = formData.endTime.replace(/-/g, '.');
  }
  auditSubmit(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>