<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="110px">
            <el-form-item label="对应地块" prop="landBlockId">
              <el-select v-model="queryParams.landBlockId" clearable placeholder="请选择对应地块">
                <el-option v-for="item in landBlockList" :key="item.id" :label="item.landName" :value="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="责任人" prop="responsiblePerson">
              <el-input v-model="queryParams.responsiblePerson" placeholder="请输入责任人" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>
      <el-table v-loading="loading" :data="landTransferLedgerList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="土地类型" align="center" prop="landTypeName" />
        <el-table-column label="地块" align="center" prop="landName" />
        <el-table-column label="进场道路" align="center" prop="roadName" />
        <el-table-column label="设计面积" align="center" prop="designArea" />
        <el-table-column label="不签合同面积" align="center" prop="noContractArea" />
        <el-table-column label="不签合同原因" align="center" prop="noContractReason" />
        <el-table-column label="不测量面积" align="center" prop="noSurveyArea" />
        <el-table-column label="不流转原因" align="center" prop="nonTransferReason" />
        <el-table-column label="操作" align="center" fixed="right" width="200">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['land:landTransferLedger:edit']">编辑</el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" @click="handleDelete(scope.row)" v-hasPermi="['land:landTransferLedger:remove']">删除</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改项目土地流转台账对话框 -->
    <el-dialog draggable :title="dialog.title" v-model="dialog.visible" width="900px" append-to-body>
      <el-form ref="landTransferLedgerFormRef" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="对应地块" prop="landBlockId">
              <el-select v-model="form.landBlockId" clearable placeholder="请选择对应地块" @change="handleLandBlockChange">
                <el-option v-for="item in landBlockList" :key="item.id" :label="item.landName" :value="item.id" />
              </el-select> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="进场道路" prop="enterRoadId">
              <el-select v-model="form.enterRoadId" clearable placeholder="请选择对应地块">
                <el-option v-for="item in enterRoadList" :key="item.id" :label="item.roadName" :value="item.id" />
              </el-select> </el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="土地类型" prop="landType">
              <el-select v-model="form.landType" placeholder="请选择土地类型" clearable>
                <el-option v-for="dict in land_type" :key="dict.value" :label="dict.label" :value="dict.value" /> </el-select></el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="流转台账状态" prop="transferStatus">
              <el-select v-model="form.transferStatus" :disabled="!form.id" placeholder="请选择流转台账状态" clearable>
                <el-option
                  v-for="dict in land_transfer_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                /> </el-select></el-form-item
          ></el-col>
          <el-col :span="12">
            <el-form-item label="设计面积(亩)" prop="designArea">
              <el-input type="number" v-model="form.designArea" placeholder="请输入设计面积" /> </el-form-item
          ></el-col>
          <el-col :span="12"
            ><el-form-item label="责任人" prop="responsiblePerson">
              <el-input v-model="form.responsiblePerson" placeholder="请输入责任人" /> </el-form-item
          ></el-col>
          <el-col :span="12"
            ><el-form-item label="预计完成日期" prop="expectedFinishDate">
              <el-date-picker clearable v-model="form.expectedFinishDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择预计完成时间">
              </el-date-picker> </el-form-item
          ></el-col>

          <el-col v-if="form.transferStatus == '1'" :span="12"
            ><el-form-item label="已流转面积(亩)" prop="transferAea">
              <el-input v-model="form.transferAea" type="number" placeholder="请输入已流转面积" /> </el-form-item
          ></el-col>
          <el-col v-if="form.transferStatus == '1'" :span="12"
            ><el-form-item label="流转比例(%)" prop="transferRatio">
              <el-input v-model="form.transferRatio" type="number" placeholder="请输入流转比例" /> </el-form-item
          ></el-col>
          <el-col v-if="form.transferStatus == '1'" :span="12">
            <el-form-item label="土地租金(元)" prop="landRent">
              <el-input type="number" v-model="form.landRent" placeholder="请输入土地租金" /> </el-form-item
          ></el-col>
          <el-col v-if="form.transferStatus == '1'" :span="12">
            <el-form-item label="青苗赔偿(元)" prop="seedlingCompensation">
              <el-input v-model="form.seedlingCompensation" type="number" placeholder="请输入青苗赔偿" /> </el-form-item
          ></el-col>
          <el-col v-if="form.transferStatus == '1'" :span="12">
            <el-form-item label="总金额(元)" prop="totalAmount">
              <el-input type="number" v-model="form.totalAmount" placeholder="请输入总金额" /> </el-form-item
          ></el-col>
          <el-col v-if="form.transferStatus == '2'" :span="12"
            ><el-form-item label="不签合同面积(亩)" prop="noContractArea">
              <el-input v-model="form.noContractArea" type="number" placeholder="请输入不签合同面积" /> </el-form-item
          ></el-col>
          <el-col v-if="form.transferStatus == '2'" :span="12">
            <el-form-item label="不测量面积(亩)" prop="noSurveyArea">
              <el-input v-model="form.noSurveyArea" type="number" placeholder="请输入不测量面积" /> </el-form-item
          ></el-col>
          <el-col v-if="form.transferStatus == '2'" :span="24"
            ><el-form-item label="不签合同原因" prop="noContractReason">
              <el-input v-model="form.noContractReason" type="textarea" placeholder="请输入内容" /> </el-form-item
          ></el-col>
          <el-col v-if="form.transferStatus == '2'" :span="24"
            ><el-form-item label="不流转原因" prop="nonTransferReason">
              <el-input v-model="form.nonTransferReason" type="textarea" placeholder="请输入内容" /> </el-form-item
          ></el-col>
          <el-col v-if="form.transferStatus == '1'" :span="24"
            ><el-form-item label="状态说明" prop="statusDescription">
              <el-input v-model="form.statusDescription" type="textarea" placeholder="请输入内容" /> </el-form-item
          ></el-col>
          <el-col v-if="form.transferStatus == '1'" :span="24"
            ><el-form-item label="问题总结" prop="issueSummary">
              <el-input v-model="form.issueSummary" type="textarea" placeholder="请输入内容" /> </el-form-item
          ></el-col>
          <el-col v-if="form.transferStatus == '1'" :span="24">
            <el-form-item label="下一步策略" prop="nextStrategy">
              <el-input v-model="form.nextStrategy" type="textarea" placeholder="请输入内容" /> </el-form-item
          ></el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="LandTransferLedger" lang="ts">
import {
  listLandTransferLedger,
  getLandTransferLedger,
  delLandTransferLedger,
  addLandTransferLedger,
  updateLandTransferLedger
} from '@/api/system/landTransfer/landTransferLedger';
import { listEnterRoad } from '@/api/system/landTransfer/enterRoad';
import { LandTransferLedgerVO, LandTransferLedgerQuery, LandTransferLedgerForm } from '@/api/system/landTransfer/landTransferLedger/types';
import { useUserStoreHook } from '@/store/modules/user';
import { listLandBlock } from '@/api/system/landTransfer/landBlock';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
// 获取用户 store
const userStore = useUserStoreHook();
// 从 store 中获取项目列表和当前选中的项目
const currentProject = computed(() => userStore.selectedProject);
const landTransferLedgerList = ref<LandTransferLedgerVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const landBlockList = ref([]);
const queryFormRef = ref<ElFormInstance>();
const landTransferLedgerFormRef = ref<ElFormInstance>();
const enterRoadList = ref([]);
const { land_type, land_transfer_status } = toRefs<any>(proxy?.useDict('land_type', 'land_transfer_status'));

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData = {
  id: undefined,
  projectId: currentProject.value?.id,
  landType: undefined,
  landBlockId: undefined,
  enterRoadId: undefined,
  designArea: undefined,
  responsiblePerson: undefined,
  expectedFinishDate: undefined,
  transferAea: undefined,
  transferRatio: undefined,
  landRent: undefined,
  seedlingCompensation: undefined,
  totalAmount: undefined,
  transferStatus: undefined,
  statusDescription: undefined,
  issueSummary: undefined,
  nextStrategy: undefined,
  noContractArea: undefined,
  noContractReason: undefined,
  noSurveyArea: undefined,
  nonTransferReason: undefined
};
const data = reactive<PageData<LandTransferLedgerForm, LandTransferLedgerQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: currentProject.value?.id,
    landType: undefined,
    landBlockId: undefined,
    enterRoadId: undefined,
    designArea: undefined,
    responsiblePerson: undefined,
    expectedFinishDate: undefined,
    transferAea: undefined,
    transferRatio: undefined,
    landRent: undefined,
    seedlingCompensation: undefined,
    totalAmount: undefined,
    transferStatus: undefined,
    statusDescription: undefined,
    issueSummary: undefined,
    nextStrategy: undefined,
    params: {},
    listType: 2
  },
  rules: {
    id: [{ required: true, message: '主键ID不能为空', trigger: 'blur' }],
    projectId: [{ required: true, message: '项目ID不能为空', trigger: 'blur' }],
    landType: [{ required: true, message: '土地类型不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询项目土地流转台账列表 */
const getList = async () => {
  loading.value = true;
  const res = await listLandTransferLedger(queryParams.value);
  landTransferLedgerList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  dialog.visible = false;
  reset();
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  landTransferLedgerFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: LandTransferLedgerVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  form.value.transferStatus = '0';
  dialog.visible = true;
  enterRoadList.value = [];
  dialog.title = '添加项目土地流转台账';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: LandTransferLedgerVO) => {
  reset();
  form.value.landBlockId = row?.landBlockId;
  getListRoad();
  const _id = row?.id || ids.value[0];
  const res = await getLandTransferLedger(_id);
  Object.assign(form.value, res.data);
  console.log(form.value);

  dialog.visible = true;
  dialog.title = '修改项目土地流转台账';
};

/** 提交按钮 */
const submitForm = () => {
  landTransferLedgerFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateLandTransferLedger(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addLandTransferLedger(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};
/** 删除按钮操作 */
const handleDelete = async (row?: LandTransferLedgerVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除项目土地流转台账编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delLandTransferLedger(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};
// 选择地块
const handleLandBlockChange = (val) => {
  getListRoad();
};
/** 查询地块信息列表 */
const getListLand = async () => {
  const res = await listLandBlock({
    pageNum: 1,
    pageSize: 10000,
    projectId: currentProject.value?.id
  });
  landBlockList.value = res.rows;
};
/** 查询进场道路信息列表 */
const getListRoad = async () => {
  const res = await listEnterRoad({ pageNum: 1, pageSize: 10000, projectId: currentProject.value?.id, landBlockId: form.value.landBlockId });
  enterRoadList.value = res.rows;
};
//监听项目id刷新数据
const listeningProject = watch(
  () => currentProject.value?.id,
  (nid, oid) => {
    queryParams.value.projectId = nid;
    getListLand();
    getList();
  }
);

onUnmounted(() => {
  listeningProject();
});
onMounted(() => {
  getList();
  getListLand();
});
</script>
