<template>
  <section class="custom-page">
    <h2>种子基本信息</h2>
    <TypeMenu v-if="materialTypes['4'].length > 1" v-model:type="_type" :types="materialTypes['4']" />
    <br />
    <avue-crud
      ref="crudRef"
      v-model:page="pageData"
      v-model:search="searchCondition"
      :table-loading="_loading"
      :before-close="handleCloseDialog"
      :data="data"
      :option="option"
      @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="deleteFn(row.id, delSeed, getData)">删除</el-button>
      </template>
      <template #photoUrl-form="{ type }"> <Attrs v-model:attrs="attrs" :type="type == 'add' ? 'add' : 'view'" :limit="2" /> </template>
    </avue-crud>
  </section>
</template>

<script setup>
import { ref, onMounted, watch, pushScopeId } from 'vue';
import TypeMenu from '../../common/TypeMenu.vue';
import { CRUD_OPTIONS, pageData, customRules } from '@/config';
import { useBasicInfo } from '@/views/inputSuppliesManage/hooks/useBasicInfo';
import Attrs from '@/views/inputSuppliesManage/common/Attrs.vue';
import inputSuppliesapi from '@/apis/inputSuppliesApi';
import { ElMessage } from 'element-plus';
import assistFn from '@/views/inputSuppliesManage/hooks/useAssistFn';
const { deleteFn } = new assistFn();
const { getSeedList, seedSave, delSeed } = inputSuppliesapi;
const { loadFinish, materialTypes, targetName } = useBasicInfo({
  moduleType: '4',
});
const _allTypes = ref([]);
watch(
  () => loadFinish.value,
  (bol) => {
    if (bol) {
      option.value.column.forEach((v) => {
        if (v.prop === '_classifyId') {
          _allTypes.value = materialTypes['4'].filter((v, i) => i > 0) ?? [];
          v.dicData = _allTypes.value;
        }
      });
    }
  }
);

onMounted(getData);
/* --------------- data --------------- */
// #region
const _type = ref('0');
const crudRef = ref();
const _loading = ref(true);
const searchCondition = ref({
  keywords: '',
});
const data = ref([]);
const option = ref({
  ...CRUD_OPTIONS,
  selection: false,
  menuWidth: 160,
  column: [
    {
      label: '种子名称',
      prop: 'keywords',
      hide: true,
      search: true,
      addDisplay: false,
      viewDisplay: false,
      editDisplay: false,
    },
    {
      label: '种子名称',
      prop: 'seedName',
      rules: customRules({ msg: '请输入种子名称' }),
    },
    {
      prop: 'manufacturer',
      label: '厂家',
      rules: customRules({ msg: '请输入厂家名称' }),
    },
    {
      label: '品牌名称',
      prop: 'brand',
      rules: customRules({ msg: '请输入品牌名称' }),
    },
    {
      label: '品种名称',
      prop: 'varietyName',
      rules: customRules({ msg: '请输入品种名称' }),
    },
    {
      hide: true,
      label: '图片',
      prop: 'photoUrl',
    },
    {
      label: '分类',
      prop: '_classifyId',
      type: 'cascader',
      expandTrigger: 'click',
      dicData: [],
      rules: customRules({ msg: '请选择分类' }),
      render: ({ row }) => row.classifyName ?? '',
    },
    // {
    //   prop: 'distributor',
    //   label: '经销商',
    // },
    {
      prop: 'productUnit',
      width: '100',
      label: '产品规格',
      // editDisplay: false,
    },
    {
      label: '种植时间',
      prop: 'sowingTime',
      span: 24,
      type: 'textarea',
    },
    {
      hide: true,
      label: '种植密度',
      prop: 'plantDensity',
      span: 24,
      type: 'textarea',
    },
    {
      hide: true,
      label: '施肥管理',
      prop: 'fertilizeManage',
      span: 24,
      type: 'textarea',
    },
    {
      hide: true,
      label: '水分管理',
      prop: 'waterManage',
      span: 24,
      type: 'textarea',
    },
    {
      hide: true,
      label: '病虫害防治',
      prop: 'pestControl',
      span: 24,
      type: 'textarea',
    },
    {
      hide: true,
      label: '注意事项',
      prop: 'precautions',
      span: 24,
      type: 'textarea',
    },
  ],
});
const attrs = ref([]);
// #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,
    seedName: searchCondition.value.keywords,
  };
  if (_type.value != '0') params['classifyId'] = _type.value;
  let res = await getSeedList(params);
  if (res.code == 200) {
    data.value = res.data.records ?? [];
    pageData.value.total = res.data.total;
  }
  _loading.value = false;
}

function handleInfo(row) {
  columnSpanChange(true);
  handleAttrs(row);
  crudRef.value.rowView(row);
}
async function handleRowSave(form, done, loading) {
  const data = Object.assign({}, form);
  delete data.keywords;
  if (attrs.value.length) {
    data.photoUrl = attrs.value.map((v) => v.url).join();
  }
  if (data._classifyId.length) {
    data.photoUrl = attrs.value.map((v) => v.url).join();
  }
  data.classifyId = JSON.stringify(data._classifyId);
  delete data._classifyId;
  data.classifyName = targetName(_allTypes.value, form._classifyId, '');
  let res = await seedSave(data);
  if (res.code == 200) {
    ElMessage.success('新增成功');
    getData();
    done();
  }
  loading();
}
/* 处理展示附件 */
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()}`,
      };
    });
  }
}
function handleCloseDialog(done) {
  columnSpanChange();
  attrs.value = [];
  done();
}
function columnSpanChange(row = false) {
  let arr = ['photoUrl'];
  option.value.column.forEach((v) => {
    if (arr.includes(v.prop)) {
      if (row) {
        v.span = 24;
      } else {
        delete v.span;
      }
    }
  });
}
// #endregion
</script>

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