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

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

      <template #isIllegal="{ row }">
        <el-tag v-if="row.isIllegal == '1'" type="danger">是</el-tag>
        <el-tag v-if="row.isIllegal == '0'" type="success">否</el-tag>
      </template>

      <template #inspectionStatus="{ row }">
        <el-tag v-if="row.inspectionStatus == '1'" type="success">已结束</el-tag>
        <el-tag v-if="row.inspectionStatus == '0'">进行中</el-tag>
      </template>
    </avue-crud>

    <el-dialog v-model="infoVisible" title="巡查任务" width="800" center>
      <el-form ref="infoRef" :model="infoData" :rules="infoRules">
        <el-descriptions :title="infoData.planName || ''" :column="2">
          <el-descriptions-item label="任务编号">{{ infoData.id || '--' }}</el-descriptions-item>
          <el-descriptions-item label="任务名称">{{ infoData.planName || '--' }}</el-descriptions-item>
          <el-descriptions-item label="任务成员">{{ infoData.plantingArea || '--' }}</el-descriptions-item>
          <el-descriptions-item label="巡查类型">{{ infoData.plantingMonths || '--' }}</el-descriptions-item>
          <el-descriptions-item label="注意事项">{{ infoData.growthCycle || '--' }}</el-descriptions-item>
          <el-descriptions-item label="巡查对象">{{ infoData.note || '--' }}</el-descriptions-item>
        </el-descriptions>
        <el-descriptions :title="'巡查信息登记'"> </el-descriptions>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否违法:" prop="num">
              <el-radio-group v-model="radio1">
                <el-radio value="1" size="large">是</el-radio>
                <el-radio value="2" size="large">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="巡查情况" prop="gridName">
              <el-input
                v-model="infoData.mark"
                :autosize="{ minRows: 2, maxRows: 4 }"
                type="textarea"
                laceholder="请输入巡查情况"
                style="width: 240px"
              ></el-input>
            </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>
  </div>
</template>
<script setup>
import { reactive, ref, h } from 'vue';
import { useApp } from '@/hooks';
import { CRUD_OPTIONS } from '@/config';
import { isEmpty, downloadFile } from '@/utils';
import { useUserStore } from '@/store/modules/user';
import { getlandInspection, savelandInspection, enrolllandInspection, exportlandInspection, getAddrCropByLand } from '@/apis/land';
import { progressProps } from 'element-plus';

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 isDisabled = ref(false);
const state = reactive({
  loading: false,
  query: {
    current: 1,
    size: 10,
    taskCode: '',
    taskName: '',
    taskMembers: '',
  },
  form: {},
  selection: [],
  options: {
    ...CRUD_OPTIONS,
    addBtnText: '新增',
    updateBtnText: '确定',
    searchSpan: 6,
    searchGutter: 80,
    searchMenuPosition: 'center',
    index: true,
    column: [
      {
        label: '任务编号',
        prop: 'taskCode',
      },
      {
        label: '任务名称',
        prop: 'taskName',
      },
      {
        label: '任务成员',
        prop: 'taskMembers',
      },
      {
        label: '巡查类型',
        prop: 'inspectionType',
      },
      {
        label: '巡查对象',
        prop: 'inspectionTarget',
      },
      {
        label: '注意事项',
        prop: 'notes',
      },
      {
        label: '是否违法',
        prop: 'isIllegal',
      },
      {
        label: '状态',
        prop: 'inspectionStatus',
      },
    ],
    actions: [
      {
        name: '登记结果',
        icon: 'edit',
        event: ({ row }) => doEnroll(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 loadData = () => {
  state.loading = true;
  getlandInspection(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);
  savelandInspection(row)
    .then((res) => {
      if (res.code === 200) {
        app.$message.success('添加成功！');
        done();
        loadData();
      }
    })
    .catch((err) => {
      app.$message.error(err.msg);
    })
    .finally(() => {
      loading();
    });
};

// 编辑
const doEnroll = (row) => {
  console.info('doEnroll', row);
  // infoVisible.value = true;
  isDisabled.value = row.inspectionStatus == '1';
  crudRef.value.rowEdit(row);
};

const rowUpdate = (row, index, done, loading) => {
  console.info('登记结果');
  let parmer = {
    id: row.id || '',
    isIllegal: row.isIllegal || '0', //巡查结果是否违法（0 否，1 是）
    inspectionSituation: row.inspectionSituation || '', //巡查情况
  };
  enrolllandInspection(parmer)
    .then((res) => {
      if (res.code === 200) {
        app.$message.success('登记结果成功！');
        done();
        loadData();
      }
    })
    .catch((err) => {
      app.$message.error(err.msg);
    })
    .finally(() => {
      loading();
    });
};

// 导出
const onExport = () => {
  if (isEmpty(state.data)) {
    app.$message.error('当前暂时没有可供导出的数据！');
    return;
  }
  state.loading = true;
  const fileName = '土地巡查明细表';
  exportlandInspection(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;
};
</script>
<style scoped>
/* 使用 ::v-deep 深度选择器来穿透 scoped 样式 */
::v-deep .el-table .el-table__row {
  height: 50px; /* 调整行高，间接控制行间距 */
}

::v-deep .el-table .el-table__row td {
  padding: 8px 0; /* 调整单元格内边距，进一步微调行间距 */
}
</style>
