<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"
      @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 #menu="scope">
        <custom-table-operate :actions="state.options.actions" :data="scope" />
      </template>
    </avue-crud>

    <el-dialog v-model="infoVisible" title="种植规划" width="800" center>
      <el-form ref="infoRef" :model="infoData" :rules="infoRules">
        <el-row :gutter="20">
          <!--<el-col :span="12">
            <el-form-item label="地块:" prop="landId">
              <CustomSelect
                v-model:value="infoData.landId"
                :set="{
                  url: 'land-resource/landManage/page',
                  props: {
                    value: 'id',
                    label: 'landName',
                  },
                }"
                placeholder="请选择地块"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="面积" prop="gridName">
              <el-input v-model="infoData.gridName" placeholder="请输入面积" style="width: 240px"></el-input>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="种植产物" prop="crop">
              <el-input v-model="infoData.crop" placeholder="请输入种植产物" style="width: 240px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="种植日期" prop="planDate">
              <el-date-picker
                v-model="infoData.planDate"
                type="date"
                placeholder="请选择种植日期"
                :disabled-date="disabledDate"
                format="YYYY/MM/DD"
                value-format="YYYY/MM/DD"
                :size="size"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="种子供应商" prop="seedSupplier">
              <el-input v-model="infoData.seedSupplier" placeholder="请输入种子供应商" style="width: 240px"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年度计划" prop="planId">
              <CustomSelect
                v-model:value="infoData.planId"
                :set="{
                  url: 'land-resource/annualManage/page',
                  props: {
                    value: 'id',
                    label: 'planName',
                  },
                }"
                placeholder="请选择种植计划"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="infoCancel">取消</el-button>
          <el-button type="primary" @click="subMitInfo(infoRef)"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
    <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 { useUserStore } from '@/store/modules/user';
import { compact } from 'lodash';
import {
  getPlanList,
  savePlan,
  exportPlan,
  editAlan,
  delPlan,
  getPlantingStage,
  savePlantingStage,
  editPlantingStage,
  delPlantingStage,
} from '@/apis/land.js';
import CustomCard from '@/components/CustomCard.vue';
import CustomSelect from '@/components/CustomSelect.vue';
import { isEmpty, imageToBase64, getAssetsFile, downloadFile } from '@/utils';

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

const state = reactive({
  loading: false,
  query: {
    current: 1,
    size: 10,
  },
  form: {},
  selection: [],
  tableClumn: [
    {
      label: '地块名',
      type: 'input',
      prop: 'landName',
      disabled: true,
      search: true,
      rules: {
        required: true,
        message: '请输入',
        trigger: 'blur',
      },
    },
    { label: '地址', prop: 'address', width: '240px', showOverflowTooltip: true, disabled: true },
    {
      label: '种植产物',
      type: 'input',
      prop: 'crop',
      disabled: true,
      search: true,
      rules: {
        required: true,
        message: '请输入',
        trigger: 'blur',
      },
    },
    {
      label: '产权人',
      type: 'input',
      prop: 'owner',
      disabled: true,
      search: true,
      rules: {
        required: true,
        message: '请输入',
        trigger: 'blur',
      },
    },
    {
      label: '农用地分类',
      prop: 'landClassificationType',
      disabled: true,
    },
    {
      label: '面积',
      prop: 'area',
      disabled: true,
    },
    { label: '坐标', prop: 'coordinate', disabled: true, width: '120px', showOverflowTooltip: true },
    {
      label: '土壤类型',
      prop: 'soilType',
      disabled: true,
    },
    {
      label: '种植产物',
      prop: 'crop',
      rules: {
        required: true,
        message: '请输入',
        trigger: 'blur',
      },
    },
    {
      label: '种子供应商',
      prop: 'seedSupplier',
      disabled: true,
    },
    {
      label: '年度计划',
      prop: 'planName',
      disabled: true,
    },
    {
      label: '种植日期',
      prop: 'planDate',
      disabled: true,
    },
  ],
  options: {
    ...CRUD_OPTIONS,
    addBtn: false,
    column: [],
    actions: [
      {
        name: '编辑',
        icon: 'edit',
        event: ({ row }) => rowEdit(row),
      },
      {
        type: 'danger',
        name: '删除',
        icon: 'delete',
        event: ({ row }) => rowDel(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: '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 landClassificationType = reactive({
  0: '耕地',
  1: '果园',
  2: '茶园',
  3: '其他园地',
  4: '林地',
  5: '草地',
  6: '其他农用地',
  7: '农村宅基地',
});

const infoVisible = ref(false);
const infoRef = ref();
let infoData = reactive({
  landId: [], //土地主键id
  planId: '', //种植规划主键id
  crop: '', //种植产物
  seedSupplier: '', //供应商
  planDate: '', //种植时间
});

const infoRules = reactive({
  crop: [{ required: true, message: '请输入种植产物', trigger: 'blur' }],
  planId: [{ required: true, message: '请选择种植计划', trigger: 'blur' }],
  seedSupplier: [{ required: true, message: '请输入供应商', trigger: 'blur' }],
  planDate: [{ required: true, message: '请选择种植时间', trigger: 'blur' }],
});

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;
  state.options.column = JSON.parse(JSON.stringify(state.tableClumn));
  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;
};

const setCity = (row) => {
  if (!isEmpty(row.cities)) {
    row.provinceCode = row?.cities[0] ?? null;
    row.cityCode = row?.cities[1] ?? null;
    row.gridAreaCode = row?.cities[2] ?? null;
    row.townCode = row?.cities[3] ?? null;
    row.village = row?.cities[3] ?? null;
  }
};

// 新增
const rowSave = (row, done, loading) => {
  state.options.column = JSON.parse(JSON.stringify(state.tableClumn));
  console.info('新增');
  // 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) => {
  infoVisible.value = true;
  infoData = reactive({
    ...row,
  });
  // console.info('编辑');
  // row.cities = compact([row.provinceCode, row.cityCode, row.gridAreaCode ?? '', row.townCode ?? '', row.village ?? '']);
  // 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 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 = () => {
  infoVisible.value = true;
};
const subMitInfo = (formEl) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      let parmer = {
        ...infoData,
      };

      if (!parmer.id) {
        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;
        });

        parmer.landId = selectIdsVal.toString() || '';
      }

      console.info('新增种植计划', parmer);

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

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

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

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 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>
