<template>
  <div class="custom-page">
    <avue-crud
      ref="crudRef"
      v-model="state.form"
      v-model:search="state.query"
      v-model:page="state.pageData"
      :table-loading="state.loading"
      :data="state.data"
      :option="state.options"
      @refresh-change="refreshChange"
      @search-reset="searchChange"
      @search-change="searchChange"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @row-save="rowSave"
      @row-update="rowUpdate"
      @row-del="rowDel"
    >
      <template #menu-left>
        <el-button type="danger" icon="delete" @click="onDel(state.selection)">批量删除</el-button>
        <el-button type="success" icon="upload" @click="onUpload">导入</el-button>
        <el-button type="success" icon="download" @click="onExport">导出</el-button>
      </template>

      <template #id="{ row }">
        <el-image style="width: 50px; height: 50px; cursor: pointer" :src="row.orCodeUrl" fit="cover" lazy @click="onViewCode(row)" />
      </template>

      <template #productUrl-form="{ column }">
        <el-upload class="custom-form__uploader" action="#" :show-file-list="false" accept="image/*" :limit="1" :http-request="rowUploadPicture">
          <img v-if="state.form.base64" :src="state.form.base64" class="custom-form__uploader__img" />
          <el-icon v-else class="custom-form__uploader__icon"><Plus /></el-icon>
        </el-upload>
      </template>

      <template #customInfo-form="{ column }">
        <custom-info :row="state.currentRow" />
      </template>

      <template #menu="scope">
        <custom-table-operate :actions="state.options.actions" :data="scope" />
      </template>
    </avue-crud>

    <custom-import-excel
      ref="importExcelRef"
      :template-url="getAssetsFile('template/采收赋码-导入模板.xlsx')"
      @on-download="onDownloadExcel"
      @on-confirm="onUploadExcel"
    />

    <code-dialog ref="codeRef" :row="state.currentRow" />

    <custom-quality-add ref="qualityAddRef" :row="state.currentRow" />
  </div>
</template>
<script setup>
import { reactive, ref } from 'vue';
import { useApp } from '@/hooks';
import { CRUD_OPTIONS } from '@/config';
import { isEmpty, imageToBase64, getAssetsFile, downloadFile } from '@/utils';
import { useUserStore } from '@/store/modules/user';
import { CommonUpload } from '@/apis';
import { compact } from 'lodash';
import { GetEntityList, AddEntity, UpdateEntity, DeleteEntity, ImportEntity, ExportEntity } from '@/apis/coding';
import CustomInfo from './info.vue';
import CustomQualityAdd from '../quality/form.vue';

const { VITE_APP_BASE_API } = import.meta.env;
const app = useApp();
const UserStore = useUserStore();
const crudRef = ref(null);
const importExcelRef = ref(null);
const qualityAddRef = ref(null);
const codeRef = ref(null);
const state = reactive({
  loading: false,
  query: {
    current: 1,
    size: 10,
  },
  form: {},
  selection: [],
  options: {
    ...CRUD_OPTIONS,
    addBtnText: '添加信息',
    column: [
      {
        label: '溯源码',
        prop: 'id',
        search: true,
        addDisplay: false,
        editDisplay: false,
        viewDisplay: true,
      },
      {
        label: '采收批次',
        prop: 'harvestBatch',
        width: 200,
        addDisplay: false,
        editDisplay: false,
        viewDisplay: true,
      },
      {
        label: '产品名称',
        prop: 'productName',
        search: true,
        width: 200,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '产品种类',
        prop: 'productType',
        type: 'select',
        search: true,
        props: {
          label: 'dictLabel',
          value: 'dictValue',
        },
        dicUrl: `${VITE_APP_BASE_API}/system/dict/data/list?pageNum=1&pageSize=20&dictType=sys_product_type`,
        dicHeaders: {
          authorization: UserStore.token,
        },
        dicFormatter: (res) => res?.data?.records ?? [],
        rules: {
          required: true,
          message: '请选择',
          trigger: 'blur',
        },
      },
      {
        label: '数量',
        prop: 'number',
        type: 'number',
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '单位',
        prop: 'unit',
        type: 'select',
        props: {
          label: 'dictLabel',
          value: 'dictValue',
        },
        dicUrl: `${VITE_APP_BASE_API}/system/dict/data/list?pageNum=1&pageSize=20&dictType=sys_unit_type`,
        dicHeaders: {
          authorization: UserStore.token,
        },
        dicFormatter: (res) => res?.data?.records ?? [],
        rules: {
          required: true,
          message: '请选择',
          trigger: 'blur',
        },
      },
      {
        label: '保质期',
        prop: 'qualityGuaranteePeriod',
        type: 'number',
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
        formatter: (row) => {
          return row.qualityGuaranteePeriod + '天';
        },
      },
      // {
      //   label: '质检结果',
      //   prop: 'qualityResult',
      //   display: false,
      // },
      // {
      //   label: '质检报告',
      //   prop: 'qualityReportUrl',
      //   display: false,
      //   slot: true,
      // },
      {
        label: '采收日期',
        prop: 'datetime',
        type: 'datetimerange',
        searchRange: true,
        search: true,
        searchSpan: 8,
        rangeSeparator: '至',
        startPlaceholder: '开始日期',
        endPlaceholder: '结束日期',
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        width: 200,
        hide: true,
        display: false,
      },
      {
        label: '采收日期',
        prop: 'harvestTime',
        type: 'date',
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        width: 200,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '省',
        prop: 'province',
        hide: true,
        display: false,
      },
      {
        label: '市',
        prop: 'city',
        hide: true,
        display: false,
      },
      {
        label: '县/区',
        prop: 'county',
        hide: true,
        display: false,
      },
      {
        label: '乡镇',
        prop: 'village',
        hide: true,
        display: false,
      },
      {
        label: '原产地',
        prop: 'originAddress',
        addDisplay: false,
        editDisplay: false,
        viewDisplay: true,
        overHidden: true,
        width: 200,
      },
      {
        label: '原产地',
        prop: 'cities',
        type: 'cascader',
        // search: true,
        hide: true,
        addDisplay: true,
        editDisplay: true,
        viewDisplay: false,
        props: {
          label: 'areaName',
          value: 'areaCode',
          children: 'areaChildVOS',
        },
        dicUrl: `${VITE_APP_BASE_API}/system/area/region?areaCode=530000`,
        dicHeaders: {
          authorization: UserStore.token,
        },
        dicFormatter: (res) => res.data ?? [],
        // change: (o) => setCityChange(o),
        rules: {
          required: true,
          message: '请选择',
          trigger: 'blur',
        },
      },
      {
        label: '原产地详细地址',
        prop: 'originAddressDetail',
        hide: true,
        viewDisplay: false,
      },
      // {
      //   label: '经营主体',
      //   prop: 'businessName',
      //   search: true,
      //   rules: {
      //     required: true,
      //     message: '请输入',
      //     trigger: 'blur',
      //   },
      // },
      {
        label: '产品图片',
        prop: 'productUrl',
        type: 'upload',
        span: 24,
        hide: true,
        formslot: true,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '农事记录',
        prop: 'farmRecord',
        type: 'textarea',
        span: 24,
        rows: 4,
        overHidden: true,
        width: 200,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '创建时间',
        prop: 'createTime',
        width: 200,
        display: false,
      },
      {
        label: '',
        labelWidth: 0,
        prop: 'customInfo',
        addDisplay: false,
        editDisplay: false,
        viewDisplay: true,
        span: 24,
      },
    ],
    actions: [
      {
        name: '查看',
        icon: 'view',
        event: ({ row }) => rowView(row),
      },
      {
        name: '编辑',
        icon: 'edit',
        event: ({ row }) => rowEdit(row),
      },
      {
        type: 'danger',
        name: '删除',
        icon: 'delete',
        event: ({ row }) => rowDel(row),
      },
      {
        name: '新增质检',
        icon: 'plus',
        event: ({ row }) => rowAdd(row),
      },
    ],
  },
  pageData: {
    total: 0,
    currentPage: 1,
    pageSize: 10,
  },
  data: [],
  currentRow: {},
});

// 加载
const loadData = () => {
  state.loading = true;
  delete state.query.datetime;
  GetEntityList(state.query)
    .then((res) => {
      if (res.code === 200) {
        const { current, size, total, records } = res.data;
        state.data = records;
        state.pageData = {
          currentPage: current || 1,
          pageSize: size || 10,
          total: total,
        };
      }
    })
    .catch((err) => {
      app.$message.error(err.msg);
      state.data = [];
    })
    .finally(() => {
      state.loading = false;
    });
};

loadData();

// 页数
const currentChange = (current) => {
  state.query.current = current;
  loadData();
};

// 条数
const sizeChange = (size) => {
  state.query.size = size;
  loadData();
};

// 搜索
const searchChange = (params, done) => {
  if (done) done();
  if (params?.datetime) {
    params.harvestStartTime = params.datetime[0];
    params.harvestEndTime = params.datetime[1];
  }
  delete params.datetime;
  state.query = params;
  state.query.current = 1;
  loadData();
};

// 刷新
const refreshChange = () => {
  loadData();
  app.$message.success('刷新成功');
};

// 选择
const selectionChange = (rows) => {
  state.selection = rows;
};

// 查看
const rowView = (row) => {
  row.base64 = row.productUrl;
  state.currentRow = row;
  crudRef.value.rowView(row);
};

// 上传图片
const rowUploadPicture = async ({ file }) => {
  if (isEmpty(file.name)) return;
  const formData = new FormData();
  formData.append('file', file);
  const res = await CommonUpload(formData);
  if (res.code === 200) {
    state.form.productUrl = res.data.url;
    const base64 = await imageToBase64(file);
    state.form.base64 = base64;
  }
};

const setCity = (row) => {
  if (!isEmpty(row.cities)) {
    row.province = row?.cities[0] ?? null;
    row.city = row?.cities[1] ?? null;
    row.county = row?.cities[2] ?? null;
    row.village = row?.cities[3] ?? null;
  }
};

function findLabelByValue(tree = [], targetValue) {
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.areaCode === targetValue) {
      return node.areaName;
    }
    if (node.areaChildVOS && node.areaChildVOS.length > 0) {
      const result = findLabelByValue(node.areaChildVOS, targetValue);
      if (result) {
        return result;
      }
    }
  }
  return null;
}

const setCityChange = ({ value, dic }) => {
  const labels = [];
  value.forEach((val) => {
    const label = findLabelByValue(dic, val);
    if (label) {
      labels.push(label);
    }
  });
  state.form.originAddress = labels.join('');
};

// 新增
const rowSave = (row, done, loading) => {
  delete row.base64;
  setCity(row);
  AddEntity(row)
    .then((res) => {
      if (res.code === 200) {
        app.$message.success('添加成功！');
        done();
        loadData();
      }
    })
    .catch((err) => {
      app.$message.error(err.msg);
    })
    .finally(() => {
      loading();
    });
};

// 编辑
const rowEdit = (row) => {
  row.base64 = row.productUrl;
  row.cities = compact([row.province, row.city, row.county ?? '', row.village ?? '']);
  crudRef.value.rowEdit(row);
};
const rowUpdate = (row, index, done, loading) => {
  delete row.base64;
  setCity(row);
  UpdateEntity(row)
    .then((res) => {
      if (res.code === 200) {
        app.$message.success('更新成功！');
        done();
        loadData();
      }
    })
    .catch((err) => {
      app.$message.error(err.msg);
    })
    .finally(() => {
      loading();
    });
};

// 删除
const onDel = (rows = []) => {
  if (isEmpty(rows)) return;
  const ids = rows.map((item) => item.id);
  app
    .$confirm(`删除后信息将不可查看，确认要删除吗？`, '确定删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      DeleteEntity({ ids: ids.join(',') })
        .then((res) => {
          if (res.code === 200) {
            app.$message.success('删除成功！');
            loadData();
          }
        })
        .catch((err) => {
          app.$message.error(err.msg);
        });
    })
    .catch(() => {});
};

const rowDel = (row, index, done) => {
  onDel([row]);
};

// 质检
const rowAdd = (row) => {
  state.currentRow = row;
  qualityAddRef?.value && qualityAddRef.value.show();
};

// 导入
const onUpload = () => {
  importExcelRef?.value && importExcelRef.value.show();
};

const onUploadExcel = (formData) => {
  ImportEntity(formData)
    .then((res) => {
      if (res.status === 200) {
        app.$message.success('导入成功！');
      }
    })
    .catch((err) => {
      app.$message.error('导入失败！');
      importExcelRef.value.clear();
    })
    .finally(() => {
      importExcelRef.value.hide();
    });
};

const onDownloadExcel = (url) => {
  downloadFile(url, `采收赋码-导入模板.xlsx`);
};

// 导出
const onExport = () => {
  if (isEmpty(state.data)) {
    app.$message.error('当前暂时没有可供导出的数据！');
    return;
  }
  state.loading = true;
  const fileName = '采收与赋码明细表';
  ExportEntity(state.query)
    .then((res) => {
      if (res.status === 200) {
        downloadFile(res.data, `${fileName}.xlsx`, 'blob');
        app.$message.success('导出成功！');
      }
    })
    .catch((err) => {
      app.$message.error('导出失败！');
    })
    .finally(() => {
      state.loading = false;
    });
};

const onViewCode = (row) => {
  state.currentRow = row;
  codeRef?.value && codeRef.value.show();
};
</script>
