<template>
  <section class="custom-page">
    <h2>肥料基本信息</h2>
    <TypeMenu v-if="materialTypes[1].length > 1" v-model:type="_type" :types="materialTypes['2']" />
    <br />
    <avue-crud
      ref="crud"
      v-model:page="pageData"
      v-model:search="searchCondition"
      :data="data"
      :table-loading="_loading"
      :option="option"
      :before-close="handleCloseDialog"
      @search-change="
        (form, done) => {
          getData(1);
          done();
        }
      "
      @refresh-change="getData"
      @search-reset="getData(1)"
      @current-change="getData"
      @size-change="getData(1)"
      @row-save="handleRowSave"
    >
      <template #menu="{ row }">
        <el-button type="primary" @click="handleInfo(row)">详情</el-button>
        <el-button @click="handleDelFn(row.id, delFretilize, getData)">删除</el-button>
      </template>
      <template #photoUrl-form="{ type }">
        <Attrs v-model:attrs="attrs" :type="type == 'add' ? 'add' : 'view'" :limit="2" />
      </template>
      <template #_productSpecification-form="{ value, type }">
        <NumberSelect v-if="type == 'add'" v-model:value="productSpecification" :options="goodsUnitOptions" />
        <span v-if="type == 'view'">{{ value }}</span>
      </template>
      <template #_suggest-form="{ value, type }">
        <NumberSelect v-if="type == 'add'" v-model:value="useDosage" :options="useDosageUnit" />
        <span v-if="type == 'view'">{{ value }}</span>
      </template>
    </avue-crud>
  </section>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import TypeMenu from '../../common/TypeMenu.vue';
import { CRUD_OPTIONS, customRules } from '@/config';
import { useBasicInfo } from '@/views/inputSuppliesManage/hooks/useBasicInfo';
import inputSuppliesApi from '@/apis/inputSuppliesApi';
import Attrs from '@/views/inputSuppliesManage/common/Attrs.vue';
import NumberSelect from '@/views/inputSuppliesManage/common/NumberSelect.vue';
import { ElMessage } from 'element-plus';

const { getFertilizreList, addFertilizer, delFretilize } = inputSuppliesApi;
const { loadFinish, materialTypes, materialTwoLevel, targetName, goodsUnitOptions, useDosageUnit, handleShowName, handleNumUnit, handleDelFn } =
  useBasicInfo();

onMounted(getData);
watch(
  () => loadFinish.value,
  (bol) => {
    if (bol) {
      option.value.column[5].dicData = materialTypes['2'].filter((v, i) => i > 0) ?? [];
      option.value.column[12].dicData = materialTwoLevel?.['1']?.['3'] ?? [];
    }
  },
  {
    deep: true,
  }
);
/* --------------- data --------------- */
// #region
const _type = ref('');
watch(
  () => _type.value,
  () => {
    getData(1);
  },
  {
    deep: true,
  }
);

const crud = ref();
const _loading = ref(false);
const data = ref([]);
const searchCondition = ref({
  keywords: '',
});
const pageData = ref({
  total: 0,
  currentPage: 1,
  size: 10,
});
const option = ref({
  ...CRUD_OPTIONS,
  selection: false,
  menuWidth: 160,
  column: [
    {
      hide: true,
      prop: 'keywords',
      label: '关键字',
      addDisplay: false,
      viewDisplay: false,
      search: true,
      searchPlaceholder: '输入肥料名称',
    },
    {
      prop: 'fertilizeName',
      label: '名称',
      rules: customRules({ msg: '请输入肥料名称' }),
    },
    {
      prop: 'manufacturer',
      label: '厂家',
      rules: customRules({ msg: '请输入厂家名称' }),
    },
    {
      prop: 'photoUrl',
      label: '肥料图片',
      hide: true,
      editDisplay: false,
    },
    {
      prop: 'distributor',
      label: '经销商',
    },
    {
      prop: '_classifyId',
      label: '分类',
      type: 'cascader',
      clearable: false,
      dicData: () => [],
      rules: customRules({ msg: '请选择肥料分类' }),
      expandTrigger: 'click',
      render: ({ row }) => {
        return row.classifyName;
      },
    },
    {
      prop: 'mainComponent',
      label: '化学成分',
      rules: customRules({ msg: '请输入化学成分' }),
    },
    {
      prop: 'adaptCrops',
      label: '适用作物',
    },
    {
      hide: true,
      prop: '_productSpecification',
      label: '产品规格',
      viewDisplay: false,
    },
    {
      hide: true,
      prop: '_suggest',
      label: '建议用量1',
      viewDisplay: false,
    },
    {
      prop: 'productSpecification',
      label: '产品规格',
      addDisplay: false,
      editDisplay: false,
    },
    {
      prop: 'suggest',
      label: '建议用量',
      addDisplay: false,
      editDisplay: false,
    },
    {
      hide: true,
      prop: '_produceDosage',
      label: '剂型',
      type: 'cascader',
      dicData: [],
      viewDisplay: false,
      expandTrigger: 'click',
    },
    {
      prop: 'produceDosage',
      label: '剂型',
      addDisplay: false,
      editDisplay: false,
      render: ({ row }) => {
        return row.produceDosage;
      },
    },
    {
      prop: 'expiryDate',
      label: '保质期',
    },
    {
      hide: true,
      prop: 'usageMethod',
      label: '使用方法',
      type: 'textarea',
      span: 24,
    },
    {
      hide: true,
      prop: 'precautions',
      label: '注意事项',
      type: 'textarea',
      span: 24,
    },
  ],
});
const attrs = ref([]);
const productSpecification = ref({
  num: 1,
  type: '1',
});
const useDosage = ref({
  num: 1,
  type: '1',
});
// #endregion

/* --------------- methods --------------- */
// #region
async function getData(reset) {
  _loading.value = true;
  reset == 1 && (pageData.value.currentPage = 1);
  let params = {
    current: pageData.value.currentPage,
    size: pageData.value.size,
    fertilizeName: searchCondition.value.keywords,
  };
  _type.value != '0' && (params.classifyId = _type.value);
  let res = await getFertilizreList(params);
  _loading.value = false;
  if (res.code == 200) {
    data.value = res.data.records.map((v) => {
      v.productSpecification = handleNumUnit({ num1: v.productSpecification, unit1: v.productUnit, type: 1 });
      v.suggest = handleNumUnit({ unit1: v.productUnit, num2: v.suggestDosage, unit2: v.suggestUnit, type: -1 });
      v.produceDosage = handleShowName(v.produceDosage);
      return v;
    });
    pageData.value.total = res.data.total;
  }
}
async function handleRowSave(form, done, loading) {
  let data = {
    fertilizeName: form.fertilizeName,
    manufacturer: form.manufacturer,
    distributor: form.distributor,
    classifyId: form._classifyId[0],
    classifyName: targetName(option.value.column[5].dicData, form._classifyId, ''),
    mainComponent: form.mainComponent,
    productSpecification: productSpecification.value.num,
    productUnit: productSpecification.value.type,
    suggestDosage: useDosage.value.num,
    suggestUnit: useDosage.value.type,
    usageMethod: form.usageMethod,
    precautions: form.precautions,
    expiryDate: form.expiryDate,
    adaptCrops: form.adaptCrops,
  };
  if (attrs.value.length) {
    data.photoUrl = attrs.value.map((v) => v.url).join();
  }
  if (form._produceDosage.length) {
    let names = [];
    form._produceDosage.forEach((item) => {
      names.push(targetName(option.value.column[12].dicData, item, ''));
    });
    data.produceDosage = JSON.stringify(form._produceDosage) + '|' + JSON.stringify(names);
  }
  let res = await addFertilizer(data);
  loading();
  if (res.code == 200) {
    ElMessage.success('添加成功');
    resetOtherInfo();
    getData();
    done();
  }
}
function handleInfo(row) {
  if (row.photoUrl) {
    attrs.value = row.photoUrl.split(',').map((v, i) => {
      return { url: v, uid: `photo_${i}_${Date.now()}` };
    });
  }
  crud.value.rowView(row);
  for (let i = 0; i < option.value.column.length; i++) {
    option.value.column[i].span = 24;
    if (option.value.column[i].prop == 'photoUrl') {
      return;
    }
  }
}
function resetOtherInfo() {
  attrs.value = [];
  productSpecification.value = { num: 1, type: '1' };
  useDosage.value = { num: 1, type: '1' };
}
function handleCloseDialog(done) {
  resetOtherInfo();
  done();
  for (let i = 0; i < option.value.column.length; i++) {
    delete option.value.column[i].span;
    if (option.value.column[i].prop == 'photoUrl') return;
  }
}
// #endregion
</script>

<style lang="scss" scoped>
h2 {
  font-size: 24px;
  font-weight: bold;
  font-family: '黑体';
}
</style>
