<template>
  <section class="custom-page">
    <avue-crud
      ref="crudRef"
      v-model:search="searchCondition"
      v-model:page="pageData"
      :table-loading="_loading"
      :option="option"
      :data="tableData"
      :before-close="(done) => (handleOtherInfo(), done())"
      @search-change="
        (form, done) => {
          getData(1);
          done();
        }
      "
      @search-reset="getData(1)"
      @refresh-change="getData"
      @current-change="getData"
      @size-change="getData(1)"
      @row-save="handleRowSave"
      @row-update="handleRowUpdate"
    >
      <!-- <template #land-form="{ type }">
        <section if="type == 'add'">地块</section>
      </template> -->
      <template #menu="scope">
        <custom-table-operate :actions="actions" :data="scope" />
      </template>
      <template #report-form="{ type }">
        <Attrs v-model:attrs="attrs" :type="type" />
      </template>
      <template #buyNumber-form="{ type }">
        <NumberSelect v-if="type != 'view'" v-model:value="buyNumber" :options="useNumberOptions" :prop="useNumebrProp" />
        <span v-else>{{ buyNumber + buyUnit }}</span>
      </template>
      <template #useNumber-form="{ type }">
        <NumberSelect v-if="type != 'view'" v-model:value="useNumber" :options="useNumberOptions" :prop="useNumebrProp" />
        <span v-else>{{ useNumber + useUnit }}</span>
      </template>
    </avue-crud>
  </section>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue';
import { CRUD_OPTIONS, pageData, customRules } from '@/config';
import { useBasicInfo } from '@/views/inputSuppliesManage/hooks/useBasicInfo';
import inputSuppliesApi from '@/apis/inputSuppliesApi';
import assistFn from '@/views/inputSuppliesManage/hooks/useAssistFn';
import Attrs from '@/views/inputSuppliesManage/common/Attrs.vue';
import { ElMessage } from 'element-plus';
import { GetEntityList } from '@/apis/system/dict';
import NumberSelect from '@/views/inputSuppliesManage/common/NumberSelect.vue';

const { deleteFn } = new assistFn();
const { getUseSuperviseList, delUseSupervise, addUseSupervise, editUseSupervise } = inputSuppliesApi;
const { materialTypes, targetName } = useBasicInfo();

onMounted(() => {
  getData();
  getUseNumberDict();
});
/* --------------- tableData --------------- */
// #region
const useNumebrProp = reactive({
  label: 'dictLabel',
  value: 'dictValue',
});
const useNumberOptions = ref([]);
const buyNumber = ref({
  num: 1,
  type: '1',
});
const useNumber = ref({
  num: 1,
  type: '1',
});
const crudRef = ref(null);
const _loading = ref(true);
const searchCondition = ref({
  searchType: '',
  keywords: '',
});
const types = reactive([
  { label: '农药监管', value: '1' },
  { label: '肥料监管', value: '2' },
  { label: '兽药监管', value: '3' },
]);
const tableData = ref([{}]);
const option = ref({
  ...CRUD_OPTIONS,
  selection: false,
  dialogWidth: '50%',
  column: [
    {
      hide: true,
      search: true,
      addDisplay: false,
      editDisplay: false,
      label: '物资类型',
      prop: 'searchType',
      type: 'select',
      dicData: types,
    },
    {
      hide: true,
      search: true,
      addDisplay: false,
      editDisplay: false,
      label: '关键字',
      prop: 'keywords',
    },
    {
      editDisabled: true,
      label: '物资类型',
      prop: 'dataType',
      type: 'select',
      dicData: types,
      clearable: false,
      value: '1',
      change: handleTypeChange,
      width: 120,
    },
    {
      label: '使用者名称',
      prop: 'name',
      width: 240,
      rules: customRules({ msg: '请输入名称' }),
    },
    {
      label: '联系方式',
      prop: 'phone',
      width: 120,
      rules: customRules({ msg: '请输入联系方式' }),
    },
    {
      label: '投入品名称',
      prop: 'inputName',
      width: 240,
      rules: customRules({ msg: '请输入投入品名称' }),
    },
    {
      hide: true,
      label: '分类',
      prop: '_classifyId',
      type: 'cascader',
      dicData: [],
      value: [],
      rules: customRules({ msg: '请选择分类' }),
      viewDisplay: false,
    },
    {
      label: '分类',
      prop: 'classifyName',
      width: 200,
      overHidden: true,
      addDisplay: false,
      editDisplay: false,
    },
    {
      label: '购买量',
      prop: 'buyNumber',
      render: ({ row }) => row.buyNumber + row.buyUnit,
    },
    {
      label: '购买时间',
      type: 'date',
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
      width: 140,
      prop: 'buyTime',
      rules: customRules({ msg: '请选择购买时间' }),
    },
    {
      label: '使用量',
      prop: 'useNumber',
      render: ({ row }) => row.useNumber + row.useUnit,
    },
    {
      label: '使用时间',
      type: 'date',
      width: 140,
      format: 'YYYY-MM-DD',
      valueFormat: 'YYYY-MM-DD',
      prop: 'useTime',
    },
    {
      label: '使用对象',
      prop: 'useObject',
    },
    {
      label: '关联地块',
      prop: 'landName',
    },
  ],
  group: [
    {
      label: '农药检测',
      prop: 'pesticide',
      // addDisplay: false,
      // editDisplay: false,
      column: [
        {
          label: '检测时间',
          prop: 'detectionTime',
          type: 'date',
          valueFormat: 'YYYY-MM-DD',
          format: 'YYYY-MM-DD',
        },
        {
          label: '检测结果',
          prop: 'detectionResult',
          type: 'select',
          dicData: [
            {
              label: '合格',
              value: '0',
            },
            {
              label: '不合格',
              value: '1',
            },
          ],
        },
        {
          label: '投入品名称',
          prop: 'detectionUnit',
        },
        {
          label: '检测报告',
          prop: 'report',
        },
      ],
    },
  ],
});
const attrs = ref([]);
const actions = reactive([
  {
    name: '详情',
    icon: 'view',
    event: ({ row }) => {
      handleOtherInfo(row);
      crudRef.value.rowView(row);
    },
  },
  {
    name: '编辑',
    icon: 'edit',
    event: ({ row }) => {
      handleOtherInfo(row);
      crudRef.value.rowEdit(row);
    },
  },
  {
    type: 'danger',
    name: '删除',
    icon: 'delete',
    event: ({ row }) => deleteFn(row.id, delUseSupervise, getData),
  },
]);
const typeDictData = ref([]);
// #endregion

/* --------------- methods --------------- */
// #region
async function getUseNumberDict() {
  let res = await GetEntityList({
    dictType: 'sys_use_supervise_number',
    current: 1,
    size: 1000,
  });
  useNumberOptions.value = res?.data?.records ?? [];
  if (useNumberOptions.value.length) {
    buyNumber.value.type = useNumberOptions.value[0].dictValue;
    useNumber.value.type = useNumberOptions.value[0].dictValue;
  }
}
async function getData(reset = 0) {
  _loading.value = true;
  reset === 1 && (pageData.value.currentPage = 1);
  let res = await getUseSuperviseList({
    current: pageData.value.currentPage,
    size: pageData.value.pageSize,
    dataType: searchCondition.value.searchType,
    name: searchCondition.value.keywords,
  });
  _loading.value = false;
  if (res.code == 200) {
    tableData.value = res.data.records.map((v) => {
      return {
        ...v,
        _classifyId: v.classifyId.split(','),
      };
    });
    pageData.value.total = res.data.total;
  }
}
function handleTypeChange(val) {
  option.value.group[0].addDisplay = val.value == '1';
  option.value.group[0].editDisplay = val.value == '1';
  option.value.group[0].viewDisplay = val.value == '1';
  typeDictData.value = materialTypes[val.value].filter((v) => v.value != '0') || [];
  option.value.column[6].dicData = typeDictData.value;
}
function handleData(val) {
  let _data = Object.assign({}, val);
  _data.buyNumber = buyNumber.value.num;
  _data.buyUnit = buyNumber.value.type;
  _data.useNumber = useNumber.value.num;
  _data.useUnit = useNumber.value.type;
  _data.classifyId = val._classifyId.join();
  _data.classifyName = targetName(typeDictData.value, val._classifyId);
  if (attrs.value.length) {
    _data.detectionReport = attrs.value.map((v) => v.url).join();
  }
  delete _data.keywords;
  delete _data.searchType;
  delete _data._classifyId;
  return _data;
}
async function handleRowSave(row, done, loading) {
  let data = handleData(row);
  let res = await addUseSupervise(data);
  loading();
  if (res.code == 200) {
    ElMessage.success('保存成功');
    getData();
    done();
  }
}
async function handleRowUpdate(row, index, done, loading) {
  let data = handleData(row);
  let res = await editUseSupervise(data);
  loading();
  if (res.code == 200) {
    ElMessage.success('保存成功');
    getData();
    done();
  }
}
function handleOtherInfo(obj = {}) {
  if (!Object.keys(obj).length) {
    attrs.value = [];
    buyNumber.value = { num: 1, type: useNumberOptions.value?.[0].dictValue ?? '1' };
    useNumber.value = { num: 1, type: useNumberOptions.value?.[0].dictValue ?? '1' };
    return;
  }
  if (obj.detectionReport) {
    attrs.value = obj.detectionReport.split(',').map((v, i) => {
      {
        return {
          name: '检测报告' + i,
          url: v,
          uid: 'id_' + i + Date.now(),
        };
      }
    });
  }
  buyNumber.value = {
    num: +obj.buyNumber,
    type: obj.buyUnit,
  };
  useNumber.value = {
    num: +obj.useNumber,
    type: obj.useUnit,
  };
}
// #endregion
</script>
