<template>
  <section class="custom-page">
    <avue-crud
      ref="crudRef"
      v-model:page="pageData"
      v-model:search="searchCondition"
      :table-loading="_loading"
      :data="data"
      :option="option"
      :before-close="
        (done) => {
          handOtherInfo({}, true);
          done();
        }
      "
      @search-change="
        (form, done) => {
          getData(1);
          done();
        }
      "
      @search-reset="getData"
      @refresh-change="getData"
      @current-change="getData"
      @size-change="getData(1)"
      @row-save="handleRowSave"
      @row-update="handleRowUpdate"
    >
      <template #businessLicense-form="{ type }">
        <Attrs v-model:attrs="attrs1" :type="type" />
      </template>
      <template #productLicense-form="{ type }">
        <Attrs v-model:attrs="attrs2" :type="type" />
      </template>
      <template #registerCertificate-form="{ type }">
        <Attrs v-model:attrs="attrs3" :type="type" />
      </template>
      <template #menu="scope">
        <custom-table-operate :actions="actions" :data="scope" />
      </template>
    </avue-crud>
  </section>
</template>

<script setup>
import { ref, onMounted, reactive, render } from 'vue';
import { CRUD_OPTIONS, pageData, customRules } from '@/config';
import inputSuppliesApi from '@/apis/inputSuppliesApi';
import Attrs from '../common/Attrs.vue';
import { ElMessage } from 'element-plus';
import assistFn from '../hooks/useAssistFn';
const { getProductionDealerList, addProductionDealer, delProductionDealer, editProductionDealer } = inputSuppliesApi;
const { deleteFn } = new assistFn();

onMounted(getData);
/* --------------- data --------------- */
// #region
const crudRef = ref(null);
const _loading = ref(false);
const dealerTypes = reactive([
  { label: '农药生产经销商', value: '1' },
  { label: '肥料生产经销商', value: '2' },
  { label: '兽药生产经销商', value: '3' },
  { label: '种源生产经销商', value: '4' },
  { label: '农机生产经销商', value: '5' },
]);
const searchCondition = ref({
  _dealerType: '',
  keywords: '',
});
const data = ref([{}]);
const option = reactive({
  ...CRUD_OPTIONS,
  dialogWidth: '50%',
  column: [
    {
      hide: true,
      search: true,
      label: '经销商类型',
      prop: '_dealerType',
      searchLabelWidth: 120,
      type: 'select',
      dicData: dealerTypes,
      addDisplay: false,
      editDisplay: false,
      viewDisplay: false,
    },
    {
      search: true,
      label: '经销商名称',
      prop: 'keywords',
      searchLabelWidth: 120,
      addDisplay: false,
      editDisplay: false,
      viewDisplay: false,
      render: ({ row }) => row.companyName,
    },
    {
      label: '经销商类型',
      prop: 'text1',
      addDisplay: false,
      editDisplay: false,
      viewDisplay: false,
      render: ({ row }) => dealerTypes.find((v) => v.value == row.dataType)?.label ?? '',
    },
    {
      label: '地址',
      prop: 'text2',
      addDisplay: false,
      editDisplay: false,
      viewDisplay: false,
      render: ({ row }) => row.address,
    },
    {
      label: '证件资料',
      prop: 'text3',
      width: 280,
      addDisplay: false,
      editDisplay: false,
      viewDisplay: false,
      render: ({ row }) => handleText3(row.dataType),
    },
    {
      label: '信息录入时间',
      prop: 'text4',
      addDisplay: false,
      editDisplay: false,
      viewDisplay: false,
      render: ({ row }) => row.createTime || '',
    },
    {
      label: '信息更新时间',
      prop: 'text5',
      addDisplay: false,
      editDisplay: false,
      viewDisplay: false,
      render: ({ row }) => row.updateTime || '',
    },
  ],
  group: [
    {
      label: '企业信息',
      prop: 'dealerInfo',
      column: [
        {
          label: '企业类型',
          type: 'select',
          prop: 'dataType',
          dicData: dealerTypes,
          value: '1',
          clearable: false,
          change: (val) => handleShowColumn(val.value),
        },
        {
          label: '企业名称',
          prop: 'companyName',
          rules: customRules({ msg: '请输入企业名称' }),
        },
        {
          label: '地址',
          prop: 'address',
          rules: customRules({ msg: '请输入地址' }),
        },
        {
          label: '负责人',
          prop: 'chargePerson',
          rules: customRules({ msg: '请输入负责人' }),
        },
        {
          label: '联系方式',
          prop: 'phone',
          rules: customRules({ msg: '请输入联系方式' }),
        },
        {
          label: '经营产品',
          prop: 'operateProduct',
          rules: customRules({ msg: '请输入经营产品' }),
        },
        {
          label: '营业执照',
          prop: 'businessLicense',
          rules: [
            {
              required: true,
              message: '请上传营业执照',
              trigger: ['change', 'blur'],
              validator: (rule, value, callback) => {
                if (attrs1.value.length === 0) {
                  callback(new Error());
                } else {
                  callback();
                }
              },
            },
          ],
        },
        {
          label: '生产许可证',
          prop: 'productLicense',
          rules: [
            {
              required: true,
              message: '请上传生产许可证',
              trigger: ['change', 'blur'],
              validator: (rule, value, callback) => {
                if (attrs2.value.length === 0) {
                  callback(new Error());
                } else {
                  callback();
                }
              },
            },
          ],
        },
        {
          label: '登记证',
          prop: 'registerCertificate',
          rules: [
            {
              required: true,
              message: '请上传登记证',
              trigger: ['change', 'blur'],
              validator: (rule, value, callback) => {
                if (attrs3.value.length === 0) {
                  callback(new Error());
                } else {
                  callback();
                }
              },
            },
          ],
        },
      ],
    },
    {
      label: '巡查信息',
      prop: 'checkInfo',
      column: [
        {
          label: '单位',
          prop: 'unit',
          rules: customRules({ msg: '请输入巡查单位' }),
        },
        {
          label: '部门',
          prop: 'dept',
          rules: customRules({ msg: '请输入巡查部门' }),
        },
        {
          label: '巡查人',
          prop: 'inspector',
          rules: customRules({ msg: '请输入巡查人' }),
        },
        {
          label: '巡查时间',
          prop: 'inspectTime',
          type: 'date',
          format: 'YYYY-MM-DD',
          valueFormat: 'YYYY-MM-DD',
          rules: customRules({ msg: '请输入巡查时间' }),
        },
        {
          label: '巡查事件',
          prop: 'inspectIncident',
          rules: customRules({ msg: '请输入巡查事件' }),
        },
        {
          label: '产品是否违规',
          prop: 'isViolation',
          type: 'select',
          dicData: [
            { label: '否', value: '0' },
            { label: '是', value: '1' },
          ],
          value: '0',
          rules: customRules({ msg: '请选择' }),
        },
        {
          label: '备注',
          prop: 'remark',
          type: 'textarea',
          span: 24,
          rules: customRules({ msg: '请输入备注' }),
        },
      ],
    },
  ],
});
const actions = reactive([
  {
    name: '编辑',
    icon: 'edit',
    event: ({ row }) => {
      handOtherInfo(row);
      crudRef.value.rowEdit(row);
    },
  },
  {
    name: '详情',
    icon: 'view',
    event: ({ row }) => {
      handOtherInfo(row);
      crudRef.value.rowView(row);
    },
  },
  {
    name: '删除',
    icon: 'delete',
    event: ({ row }) => {
      deleteFn(row.id, delProductionDealer, getData);
    },
  },
]);
const text3Names = reactive({
  1: '农药登记证',
  2: '肥料登记证',
  3: '兽药GMP证书',
  5: '3C认证证书',
});
const attrs1 = ref([]);
const attrs2 = ref([]);
const attrs3 = ref([]);
// #endregion

/* --------------- methods --------------- */
// #region
function handleShowColumn(t = '1') {
  option.group[0].column[8].addDisplay = t != '4';
  option.group[0].column[8].label = text3Names[t];
}
async function getData(reset) {
  _loading.value = true;
  reset == 1 && (pageData.value.currentPage = 1);
  let params = {
    current: pageData.value.currentPage,
    size: pageData.value.size,
    companyName: searchCondition.value.keywords,
    dataType: searchCondition.value._dealerType,
  };
  let res = await getProductionDealerList(params);
  if (res.code == 200) {
    data.value = res.data.records;
    pageData.value.total = res.data.total;
  }
  _loading.value = false;
}
function handleData(row) {
  let arr = ['text1', 'text2', 'text3', 'text4', 'text5', 'keywords', '_dealerType', 'createTime', 'updateTime'];
  let data = Object.assign({}, row);
  arr.forEach((v) => {
    delete data[v];
  });
  data.businessLicense = attrs1.value.map((v) => v.url).join();
  data.productLicense = attrs2.value.map((v) => v.url).join();
  data.registerCertificate = attrs3.value.map((v) => v.url).join();
  return data;
}
function handOtherInfo(row, reset = false) {
  if (reset) {
    attrs1.value = [];
    attrs2.value = [];
    attrs3.value = [];
    return;
  }
  attrs1.value = row.businessLicense
    ? row.businessLicense.split(',').map((v, i) => {
        return {
          url: v,
          uid: `businessLicense_${i}_${Date.now()}`,
        };
      })
    : [];
  attrs2.value = row.productLicense
    ? row.productLicense.split(',').map((v, i) => {
        return {
          url: v,
          uid: `productLicense_${i}_${Date.now()}`,
        };
      })
    : [];
  attrs3.value = row.registerCertificate
    ? row.registerCertificate.split(',').map((v, i) => {
        return {
          url: v,
          uid: `registerCertificate_${i}_${Date.now()}`,
        };
      })
    : [];
}
async function handleRowSave(row, done, loading) {
  let res = await addProductionDealer(handleData(row));
  loading();
  if (res.code == 200) {
    ElMessage.success('保存成功');
    getData();
    done();
  }
}
async function handleRowUpdate(row, index, done, loading) {
  let res = await editProductionDealer(handleData(row));
  loading();
  if (res.code == 200) {
    ElMessage.success('修改成功');
    getData();
    done();
  }
}
function handleText3(t = '1') {
  let s = '营业执照、生产许可证';
  if (t != '4') s += `、${text3Names[t]}`;
  return s;
}
// #endregion
</script>
