<template>
  <div class="custom-page">
    <avue-crud
      ref="crudRef"
      v-model="state.form"
      v-model:search="state.query"
      v-model:page="state.pageData"
      :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"
      @row-click="rowClick"
    >
      <template #menu-left>
        <el-button type="primary" icon="Plus" @click="onAdd">新增</el-button>
        <el-button type="primary" icon="Upload" @click="onImport">导入</el-button>
        <el-button type="success" icon="download" @click="onExport">导出</el-button>
      </template>

      <template #landClassificationType="{ row }">
        <el-tag type="primary" :hit="true" size="small" effect="plain">
          {{ landClassificationType[row.landClassificationType] || '未知' }}
        </el-tag>
      </template>

      <template #planDate-form="{ row, column, value }">
        <el-date-picker
          v-model="infoFirst.planDate"
          type="date"
          placeholder="请选择种植日期"
          :disabled-date="disabledDate"
          format="YYYY/MM/DD"
          value-format="YYYY/MM/DD"
          :size="size"
        />
      </template>

      <template #planId="{ row }">
        {{ row.planName }}
      </template>

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

    <stageList :is-show="stageShow" :row-original="currentRowVal" @close="stageHide"></stageList>
    <historyList :is-show="historyShow" :row-original="currentRowVal" @close="historyHide"></historyList>
  </div>
</template>
<script setup>
import { reactive, ref } from 'vue';
import { useApp } from '@/hooks';
import { CRUD_OPTIONS } from '@/config';
import { useUserStore } from '@/store/modules/user';
import {
  getPlanList,
  savePlan,
  exportPlan,
  editAlan,
  delPlan,
  getPlantingStage,
  savePlantingStage,
  editPlantingStage,
  delPlantingStage,
} from '@/apis/land.js';
import { isEmpty, imageToBase64, getAssetsFile, downloadFile } from '@/utils';
import stageList from '../../component/plantPlan/component/stage.vue';
import historyList from '../../component/plantPlan/component/history.vue';

const { VITE_APP_BASE_API } = import.meta.env;
const app = useApp();
const UserStore = useUserStore();
const crudRef = ref(null);
const stateCrudRef = ref(null);
const stageOptions = reactive([
  { value: '0', label: '苗期' },
  { value: '1', label: '花果期' },
  { value: '2', label: '采收期' },
]);

const workOptions = reactive([
  { label: '作业计划1', value: '000001' },
  { label: '作业计划2', value: '000002' },
]);

let stageShow = ref(false);
let currentRowVal = reactive({});
let historyShow = ref(false);

const state = reactive({
  loading: false,
  query: {
    current: 1,
    size: 10,
  },
  form: {},
  selection: [],
  options: {
    ...CRUD_OPTIONS,
    addBtn: false,
    rowKey: 'landId',
    searchSpan: 6,
    searchGutter: 80,
    searchMenuPosition: 'center',
    column: [
      {
        label: '地块名',
        type: 'input',
        prop: 'landName',
        search: true,
        addDisplay: false,
        editDisplay: false,
        width: '180px',
        showOverflowTooltip: true,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      { label: '地址', prop: 'address', width: '240px', showOverflowTooltip: true, addDisplay: false, editDisplay: false },
      {
        label: '种植产物',
        type: 'input',
        prop: 'crop',
        search: true,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '产权人',
        type: 'input',
        prop: 'owner',
        search: true,
        addDisplay: false,
        editDisplay: false,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '农用地分类',
        prop: 'landClassificationType',
        addDisplay: false,
        editDisplay: false,
      },
      {
        label: '面积',
        prop: 'area',
        addDisplay: false,
        editDisplay: false,
      },
      { label: '坐标', prop: 'coordinate', width: '120px', showOverflowTooltip: true, addDisplay: false, editDisplay: false },
      {
        label: '土壤类型',
        prop: 'soilType',
        addDisplay: false,
        editDisplay: false,
      },
      {
        label: '种子供应商',
        prop: 'seedSupplier',
        rules: {
          required: true,
          message: '请选择',
          trigger: 'blur',
        },
      },
      {
        label: '年度计划',
        prop: 'planId',
        type: 'select',
        remote: false,
        width: '160px',
        showOverflowTooltip: true,
        props: {
          label: 'planName',
          value: 'id',
        },
        dicHeaders: {
          authorization: UserStore.token,
        },
        dicUrl: `${VITE_APP_BASE_API}/land-resource/annualManage/page`,
        dicFormatter: (res) => res.data.records ?? [],
        rules: [
          {
            required: true,
            message: '请选择',
            trigger: 'blur',
          },
        ],
      },
      {
        label: '种植日期',
        prop: 'planDate',
        width: '180px',
        rules: {
          required: true,
          message: '请选择',
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (!infoFirst.value.planDate || infoFirst.value.planDate == '') {
              callback(new Error('请选择'));
            } else {
              callback();
            }
          },
        },
      },
    ],
    actions: [
      {
        name: '编辑',
        icon: 'edit',
        event: ({ row }) => rowEdit(row),
      },
      {
        name: '种植阶段',
        icon: 'edit',
        event: ({ row }) => toStage(row),
      },
      {
        name: '规划记录',
        icon: 'Memo',
        event: ({ row }) => toHistory(row),
      },
      {
        type: 'danger',
        name: '删除',
        icon: 'delete',
        event: ({ row }) => rowDel(row),
      },
    ],
  },
  pageData: {
    total: 0,
    currentPage: 1,
    pageSize: 10,
  },
  data: [],
  currentRow: {},
});

const landClassificationType = reactive({
  0: '耕地',
  1: '果园',
  2: '茶园',
  3: '其他园地',
  4: '林地',
  5: '草地',
  6: '其他农用地',
  7: '农村宅基地',
});

let infoFirst = ref({
  planId: '', //种植规划主键id
  planDate: '',
});

const stageObj = reactive({
  0: '苗期',
  1: '花果期',
  2: '采收期',
});

// 加载
const loadData = () => {
  state.loading = true;
  getPlanList(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();
  state.query = params;
  state.query.current = 1;
  loadData();
};

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

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

const handleIds = () => {
  let datalist = state.selection.map((m) => {
    return { landId: m.landId, landName: m.landName };
  });

  let selectIdlist = uniqueObjects(datalist, 'landId');
  let selectIdsVal = selectIdlist.map((n) => {
    return n.landId;
  });

  return selectIdsVal.toString() || '';
};
// 新增
const rowSave = (row, done, loading) => {
  console.info('新增', infoFirst.value);
  row.planDate = infoFirst.value.planDate || '';
  row.landId = handleIds();
  savePlan(row)
    .then((res) => {
      if (res.code === 200) {
        app.$message.success('添加成功！');
        done();
        loadData();
      }
    })
    .catch((err) => {
      app.$message.error(err.msg);
    })
    .finally(() => {
      loading();
    });
};

// 编辑
const rowEdit = (row) => {
  console.info('编辑', row);
  crudRef.value.rowEdit(row);
};
const rowUpdate = (row, index, done, loading) => {
  console.info('更新');
  editAlan(row)
    .then((res) => {
      if (res.code === 200) {
        app.$message.success('更新成功！');
        done();
        loadData();
      }
    })
    .catch((err) => {
      app.$message.error(err.msg);
    })
    .finally(() => {
      loading();
    });
};

// 删除
const rowDel = (row, index, done) => {
  if (isEmpty(row)) return;
  app
    .$confirm(`删除后信息将不可查看，确认要删除吗？`, '确定删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      console.info('删除');
      delPlan({ id: row.id })
        .then((res) => {
          if (res.code === 200) {
            app.$message.success('删除成功！');
            // done();
            loadData();
          }
        })
        .catch((err) => {
          app.$message.error(err.msg);
        });
    })
    .catch(() => {});
};

const toStage = (row) => {
  currentRowVal = row;
  stageShow.value = true;
  console.info('toStage', currentRowVal);
};

//导入
const onImport = () => {};
// 导出
const onExport = () => {
  if (isEmpty(state.data)) {
    app.$message.error('当前暂时没有可供导出的数据！');
    return;
  }
  state.loading = true;
  const fileName = '种植规划明细表';
  exportPlan(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 onAdd = () => {
  infoFirst.value.planDate = infoFirst.value.planId = '';
  let ids = handleIds();
  if (ids == '') {
    return app.$message.error('先选择土地！');
  }
  crudRef.value.rowAdd();
};

function uniqueObjects(arr, key) {
  return arr.reduce((acc, current) => {
    const duplicate = acc.find((element) => element[key] === current[key]);
    if (!duplicate) {
      acc.push(current);
    }
    return acc;
  }, []);
}

//种植阶段相关
const rowClick = (row) => {
  state.currentRow = { ...row };
  console.info('rowClick', state.currentRow);
};

const stageHide = () => {
  stageShow.value = false;
};

const toHistory = (row) => {
  currentRowVal = row;
  historyShow.value = true;
};
const historyHide = () => {
  historyShow.value = false;
};
</script>
