<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="valueType">
              <el-select v-model="queryParams.valueType" placeholder="请选择产值类型">
                <el-option v-for="item in out_value_type" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="结算周期" prop="settlementMonth">
              <el-date-picker clearable v-model="queryParams.settlementMonth" type="month" value-format="YYYY-MM" 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:settlementValueSubcontract:add']">新增</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="settlementValueSubcontractList" @selection-change="handleSelectionChange">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="分包单位" align="center" prop="contractorName" />
        <el-table-column label="单据编码" align="center" prop="documentCode" />
        <el-table-column label="结算说明" align="center" prop="settlementDescribe" />
        <el-table-column label="产值类型" align="center" prop="valueType">
          <template #default="scope">
            <dict-tag :options="out_value_type" :value="scope.row.valueType" />
          </template>
        </el-table-column>
        <el-table-column label="结算周期" align="center" prop="settlementMonth" />
        <el-table-column label="结算日期" align="center" prop="settlementDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.settlementDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结算产值" align="center" prop="settlementValue" >
          <template #default="scope">
            <span>{{ proxy.formatPrice(scope.row.settlementValue) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="说明" align="center" prop="remark" />
        <el-table-column label="合同编码" align="center" prop="contractCode" />
        <el-table-column label="合同名称" align="center" prop="contractName" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['out:settlementValueSubcontract:edit']"
              >修改</el-button
            >
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['out:settlementValueSubcontract: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 draggable :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="settlementValueSubcontractFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="单据编码" prop="documentCode">
          <el-input v-model="form.documentCode" placeholder="请输入单据编码" />
        </el-form-item>
        <el-form-item label="结算说明" prop="settlementDescribe">
          <el-input v-model="form.settlementDescribe" placeholder="请输入结算说明" />
        </el-form-item>
        <el-form-item label="结算周期" prop="settlementMonth">
          <el-date-picker clearable v-model="form.settlementMonth" type="month" value-format="YYYY-MM" placeholder="请选择结算周期"> </el-date-picker>
        </el-form-item>
        <el-form-item label="结算日期" prop="settlementDate">
          <el-date-picker clearable v-model="form.settlementDate" type="date" value-format="YYYY-MM-DD" placeholder="请选择结算日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="产值类型" prop="valueType">
          <el-select v-model="form.valueType" placeholder="请选择产值类型">
            <el-option v-for="item in out_value_type" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="分包单位" prop="contractorId">
          <el-select v-model="form.contractorId" value-key="id" placeholder="请选择分包单位" clearable filterable @change="">
            <el-option v-for="item in contractorList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="结算产值" prop="settlementValue">
          <el-input v-model="form.settlementValue" type="number" placeholder="请输入结算产值" />
        </el-form-item>
        <el-form-item label="说明" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入说明" />
        </el-form-item>
        <el-form-item label="合同编码" prop="contractCode">
          <el-input v-model="form.contractCode" placeholder="请输入合同编码" />
        </el-form-item>
        <el-form-item label="合同名称" prop="contractName">
          <el-input v-model="form.contractName" placeholder="请输入合同名称" />
        </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="SettlementValueSubcontract" lang="ts">
import {
  listSettlementValueSubcontract,
  getSettlementValueSubcontract,
  delSettlementValueSubcontract,
  addSettlementValueSubcontract,
  updateSettlementValueSubcontract
} from '@/api/out/settlementValueSubcontract';
import {
  SettlementValueSubcontractVO,
  SettlementValueSubcontractQuery,
  SettlementValueSubcontractForm
} from '@/api/out/settlementValueSubcontract/types';
import { listContractor } from '@/api/project/contractor';
import { ContractorVO } from '@/api/project/contractor/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { out_value_type } = toRefs<any>(proxy?.useDict('out_value_type'));
import { useUserStoreHook } from '@/store/modules/user';
// 获取用户 store
const userStore = useUserStoreHook();
// 从 store 中获取项目列表和当前选中的项目
const currentProject = computed(() => userStore.selectedProject);
const settlementValueSubcontractList = ref<SettlementValueSubcontractVO[]>([]);
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 queryFormRef = ref<ElFormInstance>();
const settlementValueSubcontractFormRef = ref<ElFormInstance>();

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

const initFormData: SettlementValueSubcontractForm = {
  id: undefined,
  projectId: currentProject.value?.id,
  documentCode: undefined,
  settlementDescribe: undefined,
  valueType: undefined,
  settlementMonth: undefined,
  settlementDate: undefined,
  contractorId: undefined,
  contractorName: undefined,
  settlementValue: undefined,
  remark: undefined,
  contractCode: undefined,
  contractName: undefined,
  contractUrl: undefined
};
const data = reactive<PageData<SettlementValueSubcontractForm, SettlementValueSubcontractQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: currentProject.value?.id,
    documentCode: undefined,
    settlementDescribe: undefined,
    valueType: undefined,
    settlementMonth: undefined,
    settlementDate: undefined,
    contractorId: undefined,
    contractorName: undefined,
    settlementValue: undefined,
    contractCode: undefined,
    contractName: undefined,
    contractUrl: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键ID不能为空', trigger: 'blur' }],
    projectId: [{ required: true, message: '项目ID不能为空', trigger: 'blur' }],
    settlementMonth: [{ required: true, message: '结算周期不能为空', trigger: 'blur' }],
    settlementDate: [{ required: true, message: '结算日期不能为空', trigger: 'blur' }],
    settlementValue: [{ required: true, message: '结算产值不能为空', trigger: 'blur' }]
  }
});

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

/** 查询结算产值登记（对乙）列表 */
const getList = async () => {
  loading.value = true;
  const res = await listSettlementValueSubcontract(queryParams.value);
  settlementValueSubcontractList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

//获取分包单位
const contractorList = ref<ContractorVO[]>([]);
const getContractorList = async () => {
  const res = await listContractor({ projectId: currentProject.value?.id } as any);
  contractorList.value = res.rows;
};

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

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

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

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

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

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  getContractorList();
  dialog.title = '添加结算产值登记（对乙）';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: SettlementValueSubcontractVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  await getContractorList();
  const res = await getSettlementValueSubcontract(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改结算产值登记（对乙）';
};

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

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

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

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

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