<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-click="rowClick"
    >
      <template #menu-left>
        <el-button type="success" icon="download" @click="onExport">导出</el-button>
      </template>

      <template #status="{ row }">
        <el-tag v-if="row.status == 1" type="success" size="small">启用</el-tag>
        <el-tag v-if="row.status == 0" type="danger" size="small">禁用</el-tag>
      </template>

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

    <el-text class="mx-1" size="large">种植阶段详情</el-text>
    <div style="margin-top: 16px">
      <avue-crud
        ref="stateCrudRef"
        v-model="stageState.form"
        v-model:search="stageState.query"
        v-model:page="stageState.pageData"
        :table-loading="stageState.loading"
        :data="stageState.data"
        :option="stageState.options"
        @refresh-change="stageRefresh"
        @search-reset="stageSearch"
        @search-change="stageSearch"
        @selection-change="stageSelection"
        @current-change="stageCurrent"
        @size-change="stageSize"
        @row-del="stageRowDel"
        @row-save="stageRowSave"
        @row-update="stageRowUpdate"
      >
        <template #menu-left>
          <el-button type="primary" icon="Plus" @click="onStateAdd">新增</el-button>
        </template>

        <template #stage="{ row }">
          <el-tag size="small">{{ stageObj[row.stage] }}</el-tag>
        </template>

        <template #menu="scope">
          <custom-table-operate :actions="stageState.options.actions" :data="scope" />
        </template>
      </avue-crud>
    </div>
  </div>
</template>
<script setup>
import { reactive, ref } from 'vue';
import { useApp } from '@/hooks';
import { CRUD_OPTIONS } from '@/config';
import { isEmpty, downloadFile } from '@/utils';
import { useUserStore } from '@/store/modules/user';
import { compact } from 'lodash';
import { getPlanType, savePlanType, upPlanType, exportPlanType } from '@/apis/baseInfo';

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 stageObj = reactive({
  0: '苗期',
  1: '花果期',
  2: '采收期',
});
const workOptions = reactive([
  { planName: '作业计划1', id: '000001' },
  { planName: '作业计划2', id: '000002' },
]);
const state = reactive({
  loading: false,
  query: {
    current: 1,
    size: 10,
  },
  form: {},
  selection: [],
  options: {
    ...CRUD_OPTIONS,
    addBtnText: '新增',
    selection: false,
    column: [
      {
        label: '编号',
        prop: 'id',
        fixed: true,
        addDisplay: false,
        editDisabled: true,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '种植产物',
        prop: 'crop',
        editDisabled: false,
        showOverflowTooltip: true,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '种植时间',
        prop: 'planDate',
        type: 'date',
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        width: 160,
        rules: {
          required: true,
          message: '请选择作业日期',
          trigger: 'blur',
        },
      },
      {
        label: '状态',
        prop: 'status',
        addDisplay: false,
        editDisplay: false,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
    ],
    searchColumn: [],
    actions: [
      {
        name: '编辑',
        icon: 'edit',
        event: ({ row }) => rowEdit(row),
      },
      {
        name: ({ row }) => {
          return row.status == 1 ? '禁用' : '启用';
        },
        icon: ({ row }) => {
          return row.status == 1 ? 'Close' : 'Check';
        },
        event: ({ row }) => rowStatus(row),
      },
    ],
  },
  pageData: {
    total: 0,
    currentPage: 1,
    pageSize: 10,
  },
  data: [],
  currentRow: {},
});

const stageState = reactive({
  loading: false,
  query: {
    current: 1,
    size: 10,
  },
  form: {},
  options: {
    ...CRUD_OPTIONS,
    addBtn: false,
    selection: false,
    column: [
      {
        label: '所属阶段',
        prop: 'stage',
        type: 'select',
        search: true,
        dicData: stageOptions,
        rules: {
          required: true,
          message: '请选择',
          trigger: 'blur',
        },
      },
      {
        label: '作业计划',
        prop: 'workId',
        type: 'select',
        search: true,
        dicData: workOptions,
        rules: {
          required: true,
          message: '请选择',
          trigger: 'blur',
        },
      },
      { label: '作业时间', prop: 'coordinate', disabled: true, addDisplay: false, editDisplay: false },
      { label: '结束时间', prop: 'createTime', disabled: true, addDisplay: false, editDisplay: false },
    ],
    actions: [
      {
        name: '编辑',
        icon: 'edit',
        event: ({ row }) => stageRowEdit(row),
      },
      {
        type: 'danger',
        name: '删除',
        icon: 'delete',
        event: ({ row }) => stageRowDel(row),
      },
    ],
  },
  pageData: {
    total: 0,
    currentPage: 1,
    pageSize: 10,
  },
  data: [],
  currentRow: {},
});

// 加载
const loadData = () => {
  state.loading = true;
  getPlanType(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;
};

// 新增
const rowSave = (row, done, loading) => {
  console.info('新增', row);
  let parmer = {
    planDate: row.planDate || '',
    crop: row.crop || '',
  };
  savePlanType(parmer)
    .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 onExport = () => {
  if (isEmpty(state.data)) {
    app.$message.error('当前暂时没有可供导出的数据！');
    return;
  }
  state.loading = true;
  const fileName = '种植产物明细表';
  exportPlanType(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 rowUpdate = (row, index, done, loading) => {
  console.info('更新');
  upPlanType(row)
    .then((res) => {
      if (res.code === 200) {
        app.$message.success('更新成功！');
        done();
        loadData();
      }
    })
    .catch((err) => {
      app.$message.error(err.msg);
    })
    .finally(() => {
      loading();
    });
};

//种植阶段相关
// 刷新
const stageRefresh = () => {
  // loadData();
  app.$message.success('刷新成功');
};

const rowStatus = (row) => {
  console.info('操作状态');
  let parmer = {
    ...row,
    status: row.status == 1 ? 0 : 1,
  };
  upPlanType(parmer)
    .then((res) => {
      if (res.code === 200) {
        app.$message.success('更新成功！');
        loadData();
      }
    })
    .catch((err) => {
      app.$message.error(err.msg);
    })
    .finally(() => {});
};

const rowClick = (row) => {
  state.currentRow = { ...row };
  console.info('rowClick', state.currentRow);
  getStageList();
};
async function getStageList() {
  // stageState.loading = true;
  // getPlantingStage({ ...stageState.query, planId: state.currentRow.id })
  //   .then((res) => {
  //     if (res.code === 200) {
  //       const { current, size, total, records } = res.data;
  //       stageState.data = records || [];
  //       stageState.pageData = {
  //         currentPage: current || 1,
  //         pageSize: size || 10,
  //         total: total,
  //       };
  //     }
  //   })
  //   .catch((err) => {
  //     app.$message.error(err.msg);
  //     stageState.data = [];
  //   })
  //   .finally(() => {
  //     stageState.loading = false;
  //   });
}

const stageSearch = (params, done) => {
  if (done) done();
  stageState.query = params;
  stageState.query.current = 1;
  getStageList();
};

const stageSelection = (rows) => {
  stageState.selection = rows;
};

const stageCurrent = (current) => {
  stageState.query.current = current;
  getStageList();
};

const stageSize = (size) => {
  stageState.query.size = size;
  getStageList();
};

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

const onStateAdd = () => {
  if (!state.currentRow.id) {
    app.$message.error('请选择种植产物');
    return;
  }
  // stageInfoData.landName = state.currentRow.landName || '';
  // stageInfoData.crop = state.currentRow.crop || '';
  // stageInfoVisible.value = true;
  stateCrudRef.value.rowAdd();
};

const stageRowSave = (row, done, loading) => {
  row.planId = state.currentRow.planId;
  console.info('stageRowSave', row);
  // savePlantingStage({ ...row })
  //   .then((res) => {
  //     if (res.code === 200) {
  //       app.$message.success('添加成功！');
  //       done();
  //       getStageList();
  //     }
  //   })
  //   .catch((err) => {
  //     app.$message.error(err.msg);
  //   })
  //   .finally(() => {
  //     loading();
  //   });
};

const stageRowUpdate = (row, index, done, loading) => {
  console.info('stageRowUpdate');
  // editPlantingStage(row)
  //   .then((res) => {
  //     if (res.code === 200) {
  //       app.$message.success('更新成功！');
  //       done();
  //       getStageList();
  //     }
  //   })
  //   .catch((err) => {
  //     app.$message.error(err.msg);
  //   })
  //   .finally(() => {
  //     loading();
  //   });
};
</script>
