<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 }">
        {{ !row.status ? '是' : '否' }}
      </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="crudRef"
        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"
      >
        <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>

      <el-dialog v-model="stageInfoVisible" title="种植阶段" width="800" center>
        <el-form ref="stageInfoRef" :model="stageInfoData" :rules="stageInfoRules">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="地块:" prop="landName">
                <el-input v-model="stageInfoData.landName" placeholder="请输入地块" style="width: 240px" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="种植产物" prop="crop">
                <el-input v-model="stageInfoData.crop" placeholder="请输入种植产物" style="width: 240px" :disabled="true"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="种植阶段" prop="stage">
                <CustomSelect
                  v-model:value="stageInfoData.stage"
                  :set="{
                    url: '',
                    options: stageOptions,
                    props: {
                      value: 'value',
                      label: 'label',
                    },
                  }"
                  placeholder="请选择种植阶段"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="作业计划" prop="workId">
                <CustomSelect
                  v-model:value="stageInfoData.workId"
                  :set="{
                    url: '',
                    options: workOptions,
                    props: {
                      value: 'id',
                      label: 'planName',
                    },
                  }"
                  placeholder="请选择作业计划"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="stageCancel">取消</el-button>
            <el-button type="primary" @click="subMitStateInfo(stageInfoRef)"> 确认 </el-button>
          </div>
        </template>
      </el-dialog>
    </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 {
  getOperationRecord,
  saveOperationRecord,
  editOperationRecord,
  delOperationRecord,
  exportOperationRecord,
  getAddrCropByLand,
  importOperationRecord,
} from '@/apis/land';

const { VITE_APP_BASE_API } = import.meta.env;
const app = useApp();
const UserStore = useUserStore();
const crudRef = ref(null);
const handleLandChange = async (value, form, done) => {
  if (!value || !value.item || !value.item.id) return; // 如果没有选择任何地块，则直接返回
  let val = {};
  getAddrCropByLand(value.item?.id || '')
    .then((res) => {
      if (res.code === 200) {
        val = res.data || {};
      }
    })
    .catch((err) => {
      val = {};
    })
    .finally(() => {});
  state.form.crop = val?.crop || value.item?.crop;
  state.form.address = val?.county + val?.town + val?.village || value.item?.address;
};

const jobTypeOptions = reactive([
  { label: '施肥', value: '0' },
  { label: '杀虫', value: '1' },
  { label: '灌溉', value: '2' },
]);

const stageOptions = reactive([
  { value: '0', label: '苗期' },
  { value: '1', label: '花果期' },
  { value: '2', label: '采收期' },
]);
const state = reactive({
  loading: false,
  query: {
    current: 1,
    size: 10,
  },
  form: {},
  selection: [],
  options: {
    ...CRUD_OPTIONS,
    addBtnText: '新增',
    column: [
      {
        label: '编号',
        prop: 'executor',
        fixed: true,
        addDisplay: false,
        editDisabled: true,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '种植产物',
        prop: 'crop',
        width: '240px',
        editDisabled: true,
        showOverflowTooltip: true,
        rules: {
          required: true,
          message: '请输入',
          trigger: 'blur',
        },
      },
      {
        label: '种植时间',
        prop: 'operationDate',
        type: 'date',
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        width: 200,
        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),
      },
    ],
  },
  pageData: {
    total: 0,
    currentPage: 1,
    pageSize: 10,
  },
  data: [],
  currentRow: {},
});
const infoVisible = ref(false);
const infoRef = ref();
const infoData = reactive({
  num: '',
  name: '',
  member: [],
  type: '',
  mark: '',
  target: '',
});

const infoRules = reactive({
  num: [{ required: true, message: '请选择是否违法', trigger: 'blur' }],
  mark: [{ required: true, message: '请输入巡查情况', trigger: 'blur' }],
});

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: 'area', disabled: true },
      { label: '作业时间', prop: 'coordinate', disabled: true },
      { label: '结束时间', prop: 'createTime', disabled: true },
    ],
    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 stageObj = reactive({
  0: '苗期',
  1: '花果期',
  2: '采收期',
});
const workOptions = reactive([
  { planName: '作业计划1', id: '000001' },
  { planName: '作业计划2', id: '000002' },
]);

let stageInfoVisible = ref(false);
const stageInfoRef = ref();
let stageInfoData = reactive({
  landId: '', //土地主键id
  planId: '', //种植规划主键id
  crop: '', //种植产物
  stage: '', //所属阶段
  workId: '', //作业计划Id
  landName: '', //地块
});

const stageInfoRules = reactive({
  stage: [{ required: true, message: '请选择所属阶段', trigger: 'blur' }],
  workId: [{ required: true, message: '请选择作业计划', trigger: 'blur' }],
});

// 加载
const loadData = () => {
  state.loading = true;
  // getOperationRecord(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);
  saveOperationRecord(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 onExport = () => {
  if (isEmpty(state.data)) {
    app.$message.error('当前暂时没有可供导出的数据！');
    return;
  }
  state.loading = true;
  const fileName = '土地巡查明细表';
  // exportOperationRecord(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 subMitInfo = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      infoHide();
      console.log('submit!');
    } else {
      console.log('error submit!');
    }
  });
};

const infoCancel = () => {
  infoHide();
};

const infoHide = () => {
  infoRef.value && infoRef.value.resetFields();
  infoVisible.value = false;
};

const rowUpdate = (row, index, done, loading) => {
  console.info('更新');
  // editOperationRecord(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 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) => {
  stageInfoData.landName = row.landName ? row.landName : state.currentRow.landName || '';
  stageInfoData.landId = row.landId ? row.landId : state.currentRow.landId || '';
  stageInfoData.crop = row.crop ? row.crop : state.currentRow.crop || '';
  stageInfoData.stage = row.stage.toString() || '0';
  stageInfoVisible.value = true;
};

const stageinfoHide = () => {
  stageInfoRef.value && stageInfoRef.value.resetFields();
  stageInfoVisible.value = false;
};

const subMitStateInfo = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      let parmer = {
        planId: state.currentRow.id || '', //种植规划主键id
        stage: stageInfoData.stage || 0, //种植阶段:0->苗期,1>花果期,2->采收期
        workId: stageInfoData.workId || '',
      };

      console.info('新增种植阶段', parmer);

      if (parmer.id) {
        // editPlantingStage(parmer)
        //   .then((res) => {
        //     if (res.code === 200) {
        //       app.$message.success('编辑成功！');
        //       getStageList();
        //       stageinfoHide();
        //     }
        //   })
        //   .catch((err) => {
        //     app.$message.error(err.msg);
        //   })
        //   .finally(() => {});
      } else {
        // savePlantingStage(parmer)
        //   .then((res) => {
        //     if (res.code === 200) {
        //       getStageList();
        //       stageinfoHide();
        //       app.$message.success('添加成功！');
        //     }
        //   })
        //   .catch((err) => {
        //     app.$message.error(err.msg);
        //   })
        //   .finally(() => {});
      }
    } else {
      console.log('error submit!');
    }
  });
};

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