<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">
            <el-form-item label="上报日期" prop="reportDate">
              <el-date-picker clearable v-model="queryParams.reportDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择上报日期" />
            </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">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['out:constructionValue:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['out:constructionValue:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['out:constructionValue:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['out:constructionValue:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="constructionValueList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <!-- <el-table-column label="主键ID" align="center" prop="id" v-if="true" /> -->
        <el-table-column label="上报日期" align="center" prop="reportDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.reportDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="项目子项" align="center" prop="subProjectName" />
        <el-table-column label="分部工程" align="center" prop="categoryName" />
        <el-table-column label="分项工程" align="center" prop="progressCategoryName" />
        <el-table-column label="人工填报数量" align="center" prop="artificialNum" />
        <el-table-column label="无人机识别数量" align="center" prop="uavNum" />
        <el-table-column label="确认数量" align="center" prop="confirmNum" />
        <el-table-column label="产值" align="center" prop="outValue" />
        <!-- <el-table-column label="审核状态" align="center" prop="auditStatus" /> -->
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="210">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['out:constructionValue:edit']">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['out:constructionValue:remove']"
              >删除</el-button
            >
            <el-button link type="primary" icon="Finished" @click="handleDelete(scope.row)" v-hasPermi="['out:constructionValue:remove']"
              >审核</el-button
            >
          </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 :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="constructionValueFormRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="方阵" prop="matrixId">
          <el-cascader
            :options="matrixOptions"
            placeholder="请选择"
            :props="{ value: 'matrixId', label: 'name', emitPath: false }"
            v-model="form.matrixId"
            @clear="resetCascader(1)"
            @change="handleChange"
            clearable
          />
        </el-form-item>
        <el-form-item label="分项工程" prop="progressCategoryId">
          <el-cascader
            :options="progressCategoryList"
            v-model="form.progressCategoryId"
            @clear="resetCascader()"
            :disabled="!form.matrixId"
            @change="selectTime"
            :props="{ expandTrigger: 'hover', value: 'id', label: 'name', emitPath: false }"
            placeholder="请选择分项工程"
            clearable
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="计划日期" prop="reportDateId">
          <el-cascader
            :options="progressTimeList"
            v-model="form.reportDateId"
            :disabled="!form.progressCategoryId"
            :props="{ expandTrigger: 'hover', value: 'id', label: 'date', emitPath: false }"
            placeholder="请选择计划日期"
            @change="submitTime"
            clearable
          >
          </el-cascader>
        </el-form-item>
        <el-form-item label="人工填报数量" prop="artificialNum">
          <el-input v-model="form.artificialNum" placeholder="请输入人工填报数量" disabled />
        </el-form-item>
        <el-form-item label="无人机识别数量" prop="uavNum">
          <el-input v-model="form.uavNum" placeholder="请输入无人机识别数量" disabled />
        </el-form-item>
        <el-form-item label="上报日期" prop="planDate">
          <el-date-picker v-model="form.planDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择上报日期" />
        </el-form-item>
        <el-form-item label="确认数量" prop="confirmNum">
          <el-input v-model="form.confirmNum" placeholder="请输入确认数量" />
        </el-form-item>
        <!-- <el-form-item label="产值" prop="outValue">
          <el-input v-model="form.outValue" disabled />
        </el-form-item> -->
      </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="ConstructionValue" lang="ts">
import {
  listConstructionValue,
  getConstructionValue,
  delConstructionValue,
  addConstructionValue,
  updateConstructionValue
} from '@/api/out/constructionValue';
import { ConstructionValueVO, ConstructionValueQuery, ConstructionValueForm } from '@/api/out/constructionValue/types';
import { getProjectSquare, listProgressCategory, workScheduleList, workScheduleListDetail, workScheduleListPosition } from '@/api/progress/plan';
import { ProgressCategoryVO } from '@/api/progress/plan/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
import { useUserStoreHook } from '@/store/modules/user';
// 获取用户 store
const userStore = useUserStoreHook();
// 从 store 中获取项目列表和当前选中的项目
const currentProject = computed(() => userStore.selectedProject);
const constructionValueList = ref<ConstructionValueVO[]>([]);
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 matrixOptions = ref([]);
const progressCategoryList = ref<ProgressCategoryVO[]>([]);
const progressTimeList = ref<any[]>([]);
const queryFormRef = ref<ElFormInstance>();
const constructionValueFormRef = ref<ElFormInstance>();

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

const initFormData: ConstructionValueForm = {
  id: undefined,
  projectId: currentProject.value?.id,
  matrixId: undefined,
  progressCategoryId: undefined,
  artificialNum: undefined,
  planNum: undefined,
  planDate: undefined,
  uavNum: undefined,
  confirmNum: undefined,
  outValue: undefined,
  reportDate: undefined,
  reportDateId: undefined,
  auditStatus: undefined
};
const data = reactive<PageData<ConstructionValueForm, ConstructionValueQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: currentProject.value?.id,
    matrixId: undefined,
    progressCategoryId: undefined,
    artificialNum: undefined,
    uavNum: undefined,
    confirmNum: undefined,
    outValue: undefined,
    reportDate: undefined,
    auditStatus: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键ID不能为空', trigger: 'blur' }],
    projectId: [{ required: true, message: '项目ID不能为空', trigger: 'blur' }],
    matrixId: [{ required: true, message: '方阵id不能为空', trigger: 'blur' }],
    progressCategoryId: [{ required: true, message: '分项工程不能为空', trigger: 'blur' }],
    artificialNum: [{ required: true, message: '人工填报数量不能为空', trigger: 'blur' }],
    reportDateId: [{ required: true, message: '上报日期不能为空', trigger: 'blur' }],
    uavNum: [{ required: true, message: '无人机识别数量不能为空', trigger: 'blur' }],
    confirmNum: [{ required: true, message: '确认数量不能为空', trigger: 'blur' }],
    outValue: [{ required: true, message: '产值不能为空', trigger: 'blur' }]
  }
});

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

/** 查询施工产值列表 */
const getList = async () => {
  loading.value = true;
  const res = await listConstructionValue(queryParams.value);
  constructionValueList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

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

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

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

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

/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  const res = await getProjectSquare(currentProject.value.id);
  if (res.data.length === 0) return proxy?.$modal.msgWarning('当前项目下没有方阵，请先创建方阵');
  const isFangzhen = res.data.every((item) => item.children.length);
  if (!isFangzhen) return proxy?.$modal.msgWarning('当前项目下没有方阵，请先创建方阵');
  let matrixList = res.data.map((item) => {
    return {
      ...item,
      matrixId: item?.projectId
    };
  });
  matrixOptions.value = matrixList;
  dialog.visible = true;
  dialog.title = '添加施工产值';
};

/** 方阵选择器改变事件 */
const handleChange = async (value: number) => {
  queryParams.value.matrixId = value;
  const res = await listProgressCategory(queryParams.value);
  const data = proxy?.handleTree<ProgressCategoryVO>(res.data, 'id', 'pid');
  if (data) {
    progressCategoryList.value = data;
    console.log('🚀 ~ handleChange ~ progressCategoryList.value :', progressCategoryList.value);
  }
};

/** 分项工程选择器改变事件 */
const selectTime = async (value: string) => {
  const res = await workScheduleListDetail(value);
  console.log('🚀 ~ selectTime ~ res:', res);
  progressTimeList.value = res.rows;
};

/** 上报日期选择器改变事件 */
const submitTime = async (value: string) => {
  const data = progressTimeList.value.filter((item) => item.id === value)[0];
  console.log(data);
  form.value.uavNum = data?.aiFill;
  form.value.reportDate = data?.date;
  form.value.planNum = data?.planNumber;
  form.value.artificialNum = data?.finishedNumber;
};

/** 重置选择器 */
const resetCascader = (index?: number) => {
  if (index) {
    form.value.progressCategoryId = undefined;
  }
  form.value.reportDate = undefined;
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ConstructionValueVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getConstructionValue(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改施工产值';
};

/** 提交按钮 */
const submitForm = () => {
  constructionValueFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateConstructionValue(form.value).finally(() => (buttonLoading.value = false));
      } else {
        console.log('🚀 ~ submitForm ~ form.value :', form.value);
        await addConstructionValue(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ConstructionValueVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除施工产值编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delConstructionValue(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'out/constructionValue/export',
    {
      ...queryParams.value
    },
    `constructionValue_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});

//监听项目id刷新数据
const listeningProject = watch(
  () => currentProject.value.id,
  (nid, oid) => {
    queryParams.value.projectId = nid;
    form.value.projectId = nid;
    getList();
  }
);

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