<template>
  <CustomCard>
    <h2>农药基本信息</h2>
    <TypeMenu v-if="materialTypes[1].length > 1" v-model:type="_type" :types="materialTypes['1']" />
    <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"
      @row-update="handleRowUpdate"
    >
      <template #menu="{ row }">
        <el-button type="primary" @click="handleEdit(row)">上传报告</el-button>
        <el-button @click="handleInfo(row)">详情</el-button>
      </template>
      <template #photoUrl-form="{ type }">
        <Attrs v-model:attrs="attrs" :type="type == 'add' ? 'add' : 'view'" />
      </template>
      <template #checkInfo-form="{ row }">
        <section style="text-align: center; line-height: 58px">
          <el-button @click="handleCheckInfo('open')">查看报告</el-button>
        </section>
      </template>
      <template #checkReport-form="{ type }">
        <Attrs v-model:attrs="reportAttrs" :type="type" :up-btn="reportAttrs.length < 1" :file-num="reportAttrs.length > 0 ? 1 : 3" />
      </template>
      <template #productSpecification-form>
        <NumberSelect v-model:value="productSpecification" :options="goodsUnitOptions" />
      </template>
      <template #dosage-form>
        <NumberSelect v-model:value="useDosage" :options="useDosageUnit" />
      </template>
      <template #checkBtn-form>
        <section style="text-align: center; line-height: 58px">
          <el-button @click="handleCheckInfo('close')">关闭</el-button>
        </section>
      </template>
    </avue-crud>
  </CustomCard>
</template>

<script setup>
import { reactive, ref, watch, onMounted, h } from 'vue';
import CustomCard from '@/components/CustomCard.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 { loadFinish, materialTypes, materialTwoLevel, goodsUnitOptions, useDosageUnit, targetName, filterTypes } = useBasicInfo({
  moduleType: '1',
});
const { getPesticideList, addPesticide } = inputSuppliesApi;
onMounted(getData);

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

const dicDatas = ref({
  _targetPests: {
    one: '1',
    two: '1',
    dic: [],
  },
  _mainComponent: {
    one: '1',
    two: '2',
    dic: [],
  },
  _produceDosage: {
    one: '1',
    two: '3',
    dic: [],
  },
});
const option = ref({
  ...CRUD_OPTIONS,
  selection: false,
  labelWidth: 124,
  editBtn: false,
  delBtn: false,
  menuWidth: 220,
  dialogWidth: '60%',
  column: [
    {
      hide: true,
      label: '关键字',
      prop: 'keywords',
      search: true,
      addDisplay: false,
      editDisplay: false,
    },
    {
      prop: 'id',
      label: '农药编号',
      addDisplay: false,
      editDisplay: false,
    },
    {
      prop: 'pesticideName',
      label: '名称',
      editDisplay: false,
      rules: customRules({ msg: '请输入农药名称' }),
    },
    {
      hide: true,
      prop: 'productStandCode',
      label: '产品标准证号',
      viewDisplay: false,
      editDisplay: false,
      rules: customRules({ msg: '请输入产品标准证号' }),
    },
    {
      hide: true,
      prop: 'photoUrl',
      label: '农药图片',
      editDisplay: false,
    },
    {
      hide: true,
      prop: 'pesticideRegistCode',
      label: '农药登记证号',
      viewDisplay: false,
      editDisplay: false,
      rules: customRules({ msg: '请输登记证号' }),
    },
    {
      prop: 'manufacturer',
      label: '生产厂家',
      editDisplay: false,
      rules: customRules({ msg: '请输入生产厂家' }),
    },
    {
      prop: 'distributor',
      label: '经销商',
      editDisplay: false,
    },
    {
      prop: 'productSpecification',
      label: '产品规格',
      editDisplay: false,
      render: ({ row }) => {
        return `${row.productSpecification}${goodsUnitOptions.find((v) => v.value == row.productUnit).label}`;
      },
    },
    {
      prop: 'toxicityLevel',
      label: '毒性',
      editDisplay: false,
      value: '无毒',
    },
    {
      prop: 'dosage',
      label: '建议用量',
      editDisplay: false,
      render: ({ row }) => {
        return `${row.suggestDosage}${useDosageUnit.find((v) => v.value == row.suggestUnit).label}`;
      },
    },
    {
      prop: 'expiryDate',
      label: '保质期',
      editDisplay: false,
    },
    {
      prop: 'targetPests',
      label: '防治对象',
    },
    {
      prop: 'mainComponent',
      label: '化学成分',
    },
    {
      prop: 'produceDosage',
      label: '加工剂型',
    },
    {
      hide: true,
      prop: '_targetPests',
      label: '防治对象',
      type: 'cascader',
      multiple: true,
      dicData: [],
      value: [],
      span: 24,
      editDisplay: false,
      rules: customRules({ msg: '请选择防治对象' }),
    },
    {
      hide: true,
      prop: '_mainComponent',
      label: '化学成分',
      type: 'cascader',
      multiple: true,
      dicData: [],
      value: [],
      span: 24,
      editDisplay: false,
      rules: customRules({ msg: '请选择主要成分' }),
    },
    {
      hide: true,
      prop: '_produceDosage',
      label: '加工剂型',
      type: 'cascader',
      multiple: true,
      dicData: [],
      value: [],
      span: 24,
      editDisplay: false,
      rules: customRules({ msg: '加工剂型' }),
    },
    {
      hide: true,
      prop: 'usageMethod',
      label: '使用方法',
      type: 'textarea',
      span: 24,
      viewDisplay: false,
      editDisplay: false,
    },
    {
      hide: true,
      prop: 'precautions',
      label: '注意事项',
      type: 'textarea',
      span: 24,
      viewDisplay: false,
      editDisplay: false,
    },
    {
      labelWidth: 0,
      border: false,
      prop: 'checkInfo',
      span: 24,
      addDisplay: false,
      editDisplay: false,
    },
  ],
  group: [
    {
      label: '农药基本信息',
      prop: 'basic_info',
      addDisplay: false,
      viewDisplay: false,
      column: [
        {
          prop: 'name',
          label: '农药名称',
          editDisabled: true,
        },
        {
          prop: 'manufacturer',
          label: '生产商',
          editDisabled: true,
        },
        {
          prop: 'photoUrl',
          label: '农药图片',
          editDisabled: true,
        },
        {
          prop: 'distributor',
          label: '经销商',
          editDisabled: true,
        },
      ],
    },
    {
      label: '农药检测信息',
      prop: 'check_info',
      addDisplay: false,
      viewDisplay: false,
      column: [
        {
          prop: 'checkDate',
          label: '农药名称',
        },
        {
          prop: 'checkResult',
          label: '检测结果',
        },
        {
          prop: 'checkUnit',
          label: '检测单位',
        },
        {
          prop: 'checkConclusion',
          label: '检测结论',
        },
        {
          prop: 'checkReport',
          label: '质检报告',
          span: 24,
        },
        {
          labelWidth: 0,
          prop: 'checkBtn',
          span: 24,
          editDisplay: false,
        },
      ],
    },
  ],
});
watch(
  () => loadFinish.value,
  () => {
    if (loadFinish.value) {
      for (let key in dicDatas.value) {
        option.value.column.forEach((item) => {
          if (item.prop === key) {
            let dic = materialTwoLevel.value?.[dicDatas.value[key].one]?.[dicDatas.value[key].two] ?? [];
            dicDatas.value[key].dic = dic;
            item.dicData = dic;
          }
        });
      }
    }
  }
);
const attrs = ref([]);
const reportAttrs = 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,
    pesticideName: searchCondition.value.keywords,
  };
  _type.value != '0' && (params.classifyId = _type.value);
  let res = await getPesticideList(params);
  console.log('res --- ', res);
  _loading.value = false;
  if (res && res.code === 200) {
    data.value = res.data.records;
    pageData.value.total = res.data.total;
  }
}
function handleCloseDialog(done) {
  resetOtherInfo();
  handleCheckInfoChange();
  done();
}

async function handleRowSave(form, done, loading) {
  console.log('handleRowSave', form);
  let data = {
    pesticideName: form.pesticideName,
    productStandCode: form.productStandCode,
    pesticideRegistCode: form.pesticideRegistCode,
    manufacturer: form.manufacturer,
    distributor: form.distributor,
    toxicityLevel: form.toxicityLevel,
    usageMethod: form.usageMethod,
    precautions: form.precautions,
    expiryDate: form.expiryDate,
    productSpecification: productSpecification.value.num,
    productUnit: productSpecification.value.type,
    suggestDosage: useDosage.value.num,
    suggestUnit: useDosage.value.type,
  };
  if (attrs.value.length) {
    data.pesticidePhoto = attrs.value.map((v) => v.url).join();
  }
  if (form._targetPests.length) {
    let names = [];
    form._targetPests.forEach((item) => {
      names.push(targetName(dicDatas.value._targetPests.dic, item, ''));
    });
    data.targetPests = JSON.stringify(form._targetPests) + '|' + JSON.stringify(names);
  }
  if (form._mainComponent.length) {
    let names = [];
    form._mainComponent.forEach((item) => {
      names.push(targetName(dicDatas.value._mainComponent.dic, item, ''));
    });
    data.mainComponent = JSON.stringify(form._mainComponent) + '|' + JSON.stringify(names);
  }
  if (form._produceDosage.length) {
    let names = [];
    form._produceDosage.forEach((item) => {
      names.push(targetName(dicDatas.value._produceDosage.dic, item, ''));
    });
    data.produceDosage = JSON.stringify(form._produceDosage) + '|' + JSON.stringify(names);
  }
  let res = await addPesticide(data);
  if (res.code == 200) {
    ElMessage.success('保存成功');
    getData();
    // resetOtherInfo();
    // done();
  }
  loading();
}
function resetOtherInfo() {
  let obj = { num: 1, type: '1' };
  attrs.value = [];
  productSpecification.value = obj;
  useDosage.value = obj;
}

function handleEdit(row) {
  console.log('handleEdit', row);
  handleCheckInfoChange('open');
  attrs.value = row.map((v) => {
    return {
      url: v,
      uid: Date.now(),
    };
  });
  reportAttrs.value = row.checkReport.map((v) => {
    return {
      url: v,
      uid: Date.now(),
    };
  });
  crud.value.rowEdit(row);
}
function handleInfo(row) {
  console.log('row', row);
  crud.value.rowView(row);
}
function handleCheckInfo(type) {
  console.log('checkInfo', type);
  handleCheckInfoChange(type == 'open');
}
/* bol && 查看检测报告关闭其他信息  !bol && 关闭检测报告打开其他信息 */
function handleCheckInfoChange(bol = false) {
  console.log('bol', bol);
  option.value.group.forEach((v) => {
    v.viewDisplay = bol;
  });
  if (bol) {
    option.value.column.forEach((v) => {
      v.viewDisplay = false;
    });
  } else {
    option.value.column.forEach((v) => {
      if (!v.hide || v.prop == 'photoUrl') {
        v.viewDisplay = true;
      }
    });
  }
}
async function handleRowUpdate(form, done, loading) {
  console.log('update from -- ', form);
  loading();
}
function handleShowName(text = '') {
  if (!text || text.includes('|')) return false;
  let names = text.split('|')[1];
  console.log('names', names);
}
// #endregion
</script>

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