<template>
  <section class="custom-page">
    <h2>兽药基本信息</h2>
    <TypeMenu v-if="materialTypes['3'].length > 1" v-model:type="_type" :types="materialTypes['3']" />
    <br />
    <avue-crud
      ref="crud"
      v-model:page="pageData"
      v-model:search="searchCondition"
      :table-loading="_loading"
      :data="data"
      :option="option"
      :before-close="handleCloseDialog"
      @search-change="
        (form, done) => {
          getData(1);
          done();
        }
      "
      @search-reset="getData(1)"
      @refresh-change="getData"
      @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, delAnimalMedicine, 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>
    </avue-crud>
  </section>
</template>

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

const { defaultGet, loadFinish, materialTypes, materialTwoLevel, goodsUnitOptions, handleNumUnit, handleShowName, targetName, handleDelFn } =
  useBasicInfo();
const { getAnimalMedicineList, addAnimalMedicine, delAnimalMedicine } = inputSuppliesApi;

/* --------------- data --------------- */
// #region
const _type = ref('0');
watch(
  () => _type.value,
  () => getData(1),
  {
    deep: true,
  }
);
const searchCondition = ref({
  keywords: '',
});
const crud = ref();
const _loading = ref(true);
const data = ref([]);
const pageData = ref({
  total: 0,
  currentPage: 1,
  size: 10,
});

const option = ref({
  ...CRUD_OPTIONS,
  selection: false,
  labelWidth: 124,
  editBtn: false,
  delBtn: false,
  menuWidth: 160,
  dialogWidth: '50%',
  column: [
    {
      hide: true,
      label: '关键字',
      prop: 'keywords',
      search: true,
      addDisplay: false,
      editDisplay: false,
      viewDisplay: false,
      searchPlaceholder: '输入药品名称',
    },
    {
      prop: 'animalName',
      label: '名称',
      width: '120',
      editDisplay: false,
      rules: customRules({ msg: '请输入药品名称' }),
    },
    {
      prop: 'manufacturer',
      label: '厂家',
      rules: customRules({ msg: '请输入厂家名称' }),
    },
    {
      hide: true,
      prop: 'photoUrl',
      label: '兽药图片',
      editDisplay: false,
    },
    {
      prop: 'distributor',
      label: '经销商',
    },
    {
      prop: 'mainComponent',
      width: '200',
      label: '主要成分',
    },
    {
      prop: '_classifyId',
      label: '分类',
      type: 'cascader',
      viewDisplay: false,
      rules: customRules({ msg: '请选择分类' }),
      expandTrigger: 'click',
      render: ({ row }) => row.classifyName,
    },
    {
      prop: 'productSpecification',
      width: '100',
      label: '产品规格',
      editDisplay: false,
    },
    {
      prop: 'produceDosage',
      width: '200',
      label: '加工剂型',
      addDisplay: false,
      editDisplay: false,
    },
    {
      hide: true,
      prop: '_produceDosage',
      label: '加工剂型',
      type: 'cascader',
      dicData: [],
      value: [],
      viewDisplay: false,
      editDisplay: false,
      expandTrigger: 'click',
      rules: customRules({ msg: '加工剂型' }),
    },
    {
      prop: 'adaptAnimal',
      label: '适用动物',
    },
    {
      prop: 'expiryDate',
      label: '保质期',
    },
    {
      hide: true,
      prop: 'purpose',
      label: '作用与用途',
      type: 'textarea',
      span: 24,
    },
    {
      hide: true,
      prop: 'usageMethod',
      label: '使用方法',
      type: 'textarea',
      span: 24,
    },
    {
      hide: true,
      prop: 'precautions',
      label: '注意事项',
      type: 'textarea',
      span: 24,
    },
  ],
});
const _allTypes = ref([]);
const _suggest = ref([]);
watch(
  () => loadFinish.value,
  () => {
    if (loadFinish.value) {
      option.value.column.forEach((v) => {
        if (v.prop === '_classifyId') {
          _allTypes.value = materialTypes['3'].filter((v, i) => i > 0) ?? [];
          v.dicData = _allTypes.value;
        }
        if (v.prop === '_produceDosage') {
          _suggest.value = materialTwoLevel?.['1']?.['3'] ?? [];
          v.dicData = _suggest.value;
        }
      });
    }
  }
);
const attrs = ref([]);
const productSpecification = ref({
  num: 1,
  type: '1',
});

// #endregion

/* --------------- methods --------------- */
// #region

defaultGet(getData);
async function getData(reset) {
  _loading.value = true;
  reset == 1 && (pageData.value.currentPage = 1);
  let params = {
    current: pageData.value.currentPage,
    size: pageData.value.size,
    animalName: searchCondition.value.keywords,
  };
  _type.value != '0' && (params.classifyId = _type.value);
  let res = await getAnimalMedicineList(params);
  _loading.value = false;
  if (res && res.code === 200) {
    data.value = res.data.records;
    data.value.forEach((v) => {
      v.productSpecification = handleNumUnit({ num1: v.productSpecification, unit1: v.productUnit, type: 1 });
      v.produceDosage = handleShowName(v.produceDosage);
    });
    pageData.value.total = res.data.total;
  }
}
function handleCloseDialog(done) {
  delete option.value.column[3].span;
  resetOtherInfo();
  done();
}

async function handleRowSave(form, done, loading) {
  let data = {
    animalName: form.animalName,
    manufacturer: form.manufacturer,
    distributor: form.distributor,
    mainComponent: form.mainComponent,
    classifyId: JSON.stringify(form._classifyId),
    classifyName: targetName(_allTypes.value, form._classifyId, ''),
    productSpecification: productSpecification.value.num,
    productUnit: productSpecification.value.type,
    adaptAnimal: form.adaptAnimal,
    purpose: form.purpose,
    usageMethod: form.usageMethod,
    precautions: form.precautions,
    expiryDate: form.expiryDate,
  };
  if (form._produceDosage.length) {
    let names = [];
    form._produceDosage.forEach((item) => {
      names.push(targetName(_suggest.value, item, ''));
    });
    data.produceDosage = JSON.stringify(form._produceDosage) + '|' + JSON.stringify(names);
  }
  if (attrs.value.length) {
    data.photoUrl = attrs.value.map((v) => v.url).join();
  }
  let res = await addAnimalMedicine(data);
  loading();
  if (res.code == 200) {
    ElMessage.success('保存成功');
    getData();
    resetOtherInfo();
    done();
  }
}
function resetOtherInfo() {
  let obj = { num: 1, type: '1' };
  attrs.value = [];
  productSpecification.value = obj;
}

function handleInfo(row) {
  handleAttrs(row);
  option.value.column[3].span = 24;
  crud.value.rowView(row);
}
/* 处理展示附件 */
function handleAttrs(row = {}) {
  if (!row) {
    return;
  }
  if (row.photoUrl) {
    attrs.value = row.photoUrl.split(',').map((v, i) => {
      return {
        url: v,
        uid: `photo_${i}_${Date.now()}`,
      };
    });
  }
}
// #endregion
</script>

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