<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="100px">
            <!--            <el-form-item label="有无合同" prop="contractFlag">-->
            <!--              <el-select v-model="queryParams.contractFlag" placeholder="请选择有无合同" clearable>-->
            <!--                <el-option v-for="dict in contract_flag" :key="dict.value" :label="dict.label" :value="dict.value" />-->
            <!--              </el-select>-->
            <!--            </el-form-item>-->
            <el-form-item label="合同编号" prop="contractCode">
              <el-input v-model="queryParams.contractCode" placeholder="请输入合同编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="客户合同编号" prop="customerContractCode">
              <el-input v-model="queryParams.customerContractCode" placeholder="请输入客户合同编号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="合同名称" prop="contractName">
              <el-input v-model="queryParams.contractName" placeholder="请输入合同名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="甲方公司名称" prop="oneCustomerName">
              <el-input
                v-model="queryParams.oneCustomerName"
                placeholder="请输入甲方公司名称"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <!--            <el-form-item label="合同大类" prop="contractCategory">-->
            <!--              <el-select v-model="queryParams.contractCategory" placeholder="请选择合同大类" clearable>-->
            <!--                <el-option v-for="dict in contract_category" :key="dict.value" :label="dict.label" :value="dict.value" />-->
            <!--              </el-select>-->
            <!--            </el-form-item>-->
            <!--            <el-form-item label="合同类型" prop="contractType">-->
            <!--              <el-select v-model="queryParams.contractType" placeholder="请选择合同类型" clearable>-->
            <!--                <el-option v-for="dict in contract_type" :key="dict.value" :label="dict.label" :value="dict.value" />-->
            <!--              </el-select>-->
            <!--            </el-form-item>-->
            <el-form-item label="业务方向" prop="businessDirection">
              <el-select v-model="queryParams.businessDirection" placeholder="请选择业务方向" clearable>
                <el-option v-for="dict in business_direction" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <!--            <el-form-item label="部门" prop="contractDeptId">-->
            <!--              <el-input v-model="queryParams.contractDeptId" placeholder="请输入部门" clearable @keyup.enter="handleQuery" />-->
            <!--            </el-form-item>-->
            <el-form-item label="合同状态" prop="contractStatus">
              <el-select v-model="queryParams.contractStatus" placeholder="请选择合同状态" clearable>
                <el-option v-for="dict in contract_status" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <!--            <el-form-item label="流程状态" prop="flowStatus">-->
            <!--              <el-input v-model="queryParams.flowStatus" 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">
          <el-col :span="1.5">
            <el-dropdown trigger="click" @command="handleAdd" v-hasPermi="['oa/erp:contractInfo:add']">
              <el-button type="primary" plain icon="Plus">
                新增 <el-icon class="el-icon--right"><arrow-down /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-for="dict in contract_category" :key="dict.value" :command="dict.value">
                    {{ dict.label }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="EditPen" :disabled="single" @click="openMaintainDialog" v-hasPermi="['oa/erp:contractInfo:update']"
              >维护合同信息
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="DocumentCopy" :disabled="single" @click="openCopyDialog" v-hasPermi="['oa/erp:contractInfo:add']"
              >复制合同
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['oa/erp:contractInfo:remove']"
              >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['oa/erp:contractInfo:export']">导出 </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" :columns="columns" :search="true" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="contractInfoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="合同ID" align="center" prop="contractId" v-if="columns[0].visible" />
        <el-table-column label="有无合同" align="center" prop="contractFlag" v-if="columns[2].visible">
          <template #default="scope">
            <dict-tag :options="contract_flag" :value="scope.row.contractFlag" />
          </template>
        </el-table-column>
        <el-table-column label="合同编号" align="center" prop="contractCode" width="140" v-if="columns[3].visible" />
        <el-table-column label="合同名称" align="center" prop="contractName" width="200" v-if="columns[4].visible" />
        <el-table-column label="合同大类" align="center" prop="contractCategory" width="100" v-if="columns[5].visible">
          <template #default="scope">
            <dict-tag :options="contract_category" :value="scope.row.contractCategory" />
          </template>
        </el-table-column>
        <el-table-column label="合同类型" align="center" prop="contractType" v-if="columns[6].visible">
          <template #default="scope">
            <dict-tag :options="contract_type" :value="scope.row.contractType" />
          </template>
        </el-table-column>
        <el-table-column label="业务方向" align="center" prop="businessDirection" width="100" v-if="columns[7].visible">
          <template #default="scope">
            <dict-tag :options="business_direction" :value="scope.row.businessDirection" />
          </template>
        </el-table-column>
        <el-table-column label="部门" align="center" prop="deptName" width="100" v-if="columns[8].visible" />
        <el-table-column label="合同状态" align="center" prop="contractStatus" v-if="columns[17].visible">
          <template #default="scope">
            <dict-tag :options="contract_status" :value="scope.row.contractStatus" />
          </template>
        </el-table-column>
        <el-table-column label="合同签订日期" align="center" prop="contractDate" width="120" v-if="columns[9].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.contractDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="合同总价" align="center" prop="totalPrice" width="100" v-if="columns[10].visible" />
        <el-table-column label="甲方公司" align="center" prop="oneCustomerName" width="200" v-if="columns[11].visible" />
        <el-table-column label="甲方授权代表" align="center" prop="oneRepresent" width="110" v-if="columns[12].visible" />
        <el-table-column label="甲方签字日期" align="center" prop="aDate" width="120" v-if="columns[13].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.oneDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="乙方公司" align="center" prop="twoCustomerName" width="200" v-if="columns[14].visible" />
        <el-table-column label="乙方授权代表" align="center" prop="twoRepresent" width="110" v-if="columns[15].visible" />
        <el-table-column label="乙方签字日期" align="center" prop="twoDate" width="120" v-if="columns[16].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.twoDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="流程状态" align="center" prop="flowStatus" v-if="columns[18].visible" />
        <el-table-column label="合同模板ID" align="center" prop="templateId" v-if="columns[19].visible" />
        <el-table-column label="附件ID" align="center" prop="ossId" v-if="columns[20].visible" />
        <el-table-column label="付款方式" align="center" prop="paymentMethod" v-if="columns[21].visible" />
        <el-table-column label="签字合同附件" align="center" prop="signatureAppendix" v-if="columns[22].visible" />
        <el-table-column label="合同税率(预留)" align="center" prop="taxRate" v-if="columns[23].visible" />
        <el-table-column label="终版合同" align="center" width="120" v-if="columns[32].visible">
          <template #default="scope">
            <el-button
              v-if="scope.row.signatureAppendix"
              link
              type="primary"
              icon="Download"
              @click="downloadFinalContract(scope.row.signatureAppendix)"
            >
              下载{{ getFinalContractFileCount(scope.row.signatureAppendix) > 1 ? `(${getFinalContractFileCount(scope.row.signatureAppendix)})` : '' }}
            </el-button>
            <span v-else style="color: #999">未上传</span>
          </template>
        </el-table-column>
        <el-table-column label="客户合同编号" align="center" prop="customerContractCode" width="160" v-if="columns[33].visible" />
        <el-table-column label="海威SAP订单号" align="center" prop="internalContractCode" width="160" v-if="columns[34].visible" />
        <el-table-column label="海威合同归档编号" align="center" prop="externalContractCode" width="160" v-if="columns[35].visible" />
        <el-table-column label="软控SAP订单号" align="center" prop="orderContractCode" width="160" v-if="columns[36].visible" />
        <el-table-column label="软控SAP项目号" align="center" prop="projectContractCode" width="160" v-if="columns[37].visible" />
        <el-table-column label="软控合同额（元）" align="center" prop="mesnacContractPrice" width="160" v-if="columns[41].visible" />
        <el-table-column label="合同负责人" align="center" prop="contractManagerName" width="120" v-if="columns[38].visible" />
        <el-table-column label="合同大写金额" align="center" prop="capitalizedAmount" width="150" v-if="columns[39].visible" />
        <el-table-column label="合同模板标识" align="center" prop="contractTemplateFlag" width="120" v-if="columns[40].visible">
          <template #default="scope">
            <dict-tag :options="contract_template_flag" :value="scope.row.contractTemplateFlag" />
          </template>
        </el-table-column>
        <el-table-column label="关联框架合同" align="center" prop="isFrameworkContract" width="120" v-if="columns[42].visible">
          <template #default="scope">
            <el-tag :type="scope.row.isFrameworkContract === '1' ? 'success' : 'info'">
              {{ scope.row.isFrameworkContract === '1' ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="框架合同有效期" align="center" prop="frameworkValidPeriod" width="120" v-if="columns[43].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.frameworkValidPeriod, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="合同属地标识" align="center" prop="contractTerritorialFlag" width="120" v-if="columns[44].visible">
          <template #default="scope">
            <dict-tag :options="contract_territorial_flag" :value="scope.row.contractTerritorialFlag" />
          </template>
        </el-table-column>
        <el-table-column label="合同属地国家/地区" align="center" prop="contractTerritorialCountry" width="160" v-if="columns[45].visible">
          <template #default="scope">
            <dict-tag :options="country_region" :value="scope.row.contractTerritorialCountry" />
          </template>
        </el-table-column>
        <el-table-column label="结算币种" align="center" prop="settlementCurrency" width="110" v-if="columns[46].visible">
          <template #default="scope">
            <dict-tag :options="currency_type" :value="scope.row.settlementCurrency" />
          </template>
        </el-table-column>
        <el-table-column label="对人民币汇率" align="center" prop="rmbExchangeRate" width="120" v-if="columns[47].visible" />
        <el-table-column label="备注" align="center" prop="remark" v-if="columns[24].visible" />
        <el-table-column label="激活标识" align="center" prop="activeFlag" v-if="columns[25].visible">
          <template #default="scope">
            <dict-tag :options="active_flag" :value="scope.row.activeFlag" />
          </template>
        </el-table-column>
        <el-table-column label="创建人" align="center" prop="createBy" v-if="columns[28].visible" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" v-if="columns[29].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="更新人" align="center" prop="updateBy" v-if="columns[30].visible" />
        <el-table-column label="更新时间" align="center" prop="updateTime" width="180" v-if="columns[31].visible">
          <template #default="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180" fixed="right" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看详情" placement="top" v-if="canViewDetail(scope.row)">
              <el-button link type="info" icon="DocumentChecked" @click="handleView(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top" v-if="scope.row.contractStatus === '1'">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['oa/erp:contractInfo:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="修改并重提审批" placement="top" v-if="canReapproveAfterApproved(scope.row)">
              <el-button
                link
                type="warning"
                icon="RefreshRight"
                @click="handleReapprove(scope.row)"
                v-hasPermi="['oa/erp:contractInfo:edit']"
              ></el-button>
            </el-tooltip>
            <!--            <el-tooltip content="审批记录" placement="top" v-if="scope.row.contractStatus === '2' || scope.row.contractStatus === '3'">-->
            <!--              <el-button link type="info" icon="View" @click="handleApprovalRecord(scope.row)"></el-button>-->
            <!--            </el-tooltip>-->
            <el-tooltip content="合同下载" placement="top" v-if="scope.row.templateId != null">
              <el-button link type="info" icon="Download" @click="contractView(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="审批单导出" placement="top" v-if="scope.row.contractStatus == 3">
              <el-button link type="primary" icon="Tickets" @click="handleExportApprovalWord(scope.row)"></el-button>
            </el-tooltip>
            <!--            <el-tooltip content="合同激活" placement="top" v-if="showUploadButton(scope.row)">-->
            <!--              <el-button-->
            <!--                link-->
            <!--                type="success"-->
            <!--                icon="Upload"-->
            <!--                @click="openUploadFinalDialog(scope.row)"-->
            <!--                v-hasPermi="['oa/erp:contractInfo:edit']"-->
            <!--              ></el-button>-->
            <!--            </el-tooltip>-->
            <el-tooltip content="合同订单激活" placement="top" v-if="canActivateOrder(scope.row)">
              <el-button link type="warning" icon="CircleCheck" @click="handleOrderActivate(scope.row)"></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 v-model="uploadDialog.visible" title="合同激活" width="520px" append-to-body>
      <el-form ref="uploadFormRef" :model="uploadDialog.form" :rules="uploadFormRules" label-width="120px">
        <!-- <el-form-item label="部门" prop="contractDeptId" required>
          <el-select v-model="uploadDialog.form.contractDeptId" placeholder="请选择部门" style="width: 100%">
            <el-option v-for="item in deptInfoList" :key="item.deptId" :label="item.deptName" :value="item.deptId" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="签字合同附件" prop="oss" required>
          <fileUpload v-model="uploadDialog.form.oss" :limit="10" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :loading="uploadDialog.loading" @click="confirmUploadFinal">确 定</el-button>
          <el-button @click="uploadDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 复制合同 -->
    <el-dialog v-model="copyDialog.visible" title="复制合同信息" width="560px" append-to-body>
      <el-form ref="copyFormRef" :model="copyDialog.form" :rules="copyFormRules" label-width="100px">
        <el-form-item label="源合同">
          <el-input :model-value="copyDialog.sourceLabel" disabled />
        </el-form-item>
        <el-form-item label="合同编号" prop="contractCode">
          <el-input v-model="copyDialog.form.contractCode" placeholder="请输入或生成合同编号" clearable>
            <template #append>
              <el-button type="primary" @click="generateCopyContractCode" :disabled="copyCodeGenerated">生成合同编号</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="合同名称" prop="contractName">
          <el-input v-model="copyDialog.form.contractName" placeholder="请输入新合同名称" clearable />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="copyDialog.form.remark" type="textarea" :rows="3" placeholder="请输入备注" clearable />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :loading="copyDialog.loading" @click="submitCopy">确 定</el-button>
          <el-button @click="copyDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 维护合同信息 -->
    <el-dialog v-model="maintainDialog.visible" title="维护合同信息" width="600px" append-to-body>
      <el-form ref="maintainFormRef" :model="maintainDialog.form" label-width="150px">
        <el-form-item label="合同名称">
          <el-input v-model="maintainDialog.form.contractName" disabled />
        </el-form-item>
        <el-form-item label="合同编号">
          <el-input v-model="maintainDialog.form.contractCode" disabled />
        </el-form-item>
        <el-form-item label="海威SAP订单号">
          <el-input v-model="maintainDialog.form.internalContractCode" placeholder="请输入海威SAP订单号" />
        </el-form-item>
        <el-form-item label="海威合同归档编号">
          <el-input v-model="maintainDialog.form.externalContractCode" placeholder="请输入海威合同归档编号" />
        </el-form-item>
        <el-form-item label="软控SAP订单号">
          <el-input v-model="maintainDialog.form.orderContractCode" placeholder="请输入SAP订单号" />
        </el-form-item>
        <el-form-item label="软控SAP项目号">
          <el-input v-model="maintainDialog.form.projectContractCode" placeholder="请输入软控SAP项目号" />
        </el-form-item>
        <el-form-item label="软控合同额（元）">
          <el-input-number
            v-model="maintainDialog.form.mesnacContractPrice"
            :min="0"
            :precision="2"
            controls-position="right"
            placeholder="请输入软控合同额（元）"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" :loading="maintainDialog.loading" @click="submitMaintain">保 存</el-button>
          <el-button @click="maintainDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 审批记录 -->
    <ApprovalRecord ref="approvalRecordRef" />
  </div>
</template>

<script setup name="ContractInfo" lang="ts">
import { copyContractInfo, delContractInfo, exportContractApprovalWord, listContractInfo, updateContractInfo } from '@/api/oa/erp/contractInfo';
import { ContractInfoForm, ContractInfoQuery, ContractInfoVO } from '@/api/oa/erp/contractInfo/types';
import download from '@/plugins/download';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';
import { allListDept } from '@/api/system/dept';
import { getRuleGenerateCode } from '@/api/system/codeRule';
import { CodeRuleEnum } from '@/enums/OAEnum';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const route = useRoute();
const router = useRouter();
const { contract_category, business_direction, active_flag, contract_flag, contract_type, contract_status, contract_template_flag, contract_territorial_flag, country_region, currency_type } = toRefs<any>(
  proxy?.useDict(
    'contract_category',
    'business_direction',
    'active_flag',
    'contract_flag',
    'contract_type',
    'contract_status',
    'contract_template_flag',
    'contract_territorial_flag',
    'country_region',
    'currency_type'
  )
);

const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();
const contractInfoList = ref<ContractInfoVO[]>([]);
const selectedRows = ref<ContractInfoVO[]>([]);
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 columns = ref<FieldOption[]>([
  { key: 0, label: `合同ID`, visible: false },
  { key: 1, label: `租户编号`, visible: false },
  { key: 2, label: `有无合同`, visible: false },
  { key: 3, label: `合同编号`, visible: true },
  { key: 4, label: `合同名称`, visible: true },
  { key: 5, label: `合同大类`, visible: true },
  { key: 6, label: `合同类型`, visible: false },
  { key: 7, label: `业务方向`, visible: true },
  { key: 8, label: `部门`, visible: false },
  { key: 9, label: `合同签订日期`, visible: true },
  { key: 10, label: `合同总价`, visible: true },
  { key: 11, label: `甲方公司`, visible: true },
  { key: 12, label: `甲方授权代表`, visible: true },
  { key: 13, label: `甲方签字日期`, visible: true },
  { key: 14, label: `乙方公司`, visible: true },
  { key: 15, label: `乙方授权代表`, visible: true },
  { key: 16, label: `乙方签字日期`, visible: true },
  { key: 17, label: `合同状态`, visible: true },
  { key: 18, label: `流程状态`, visible: false },
  { key: 19, label: `合同模板ID`, visible: false },
  { key: 20, label: `附件ID`, visible: false },
  { key: 21, label: `付款方式`, visible: false },
  { key: 22, label: `签字合同附件`, visible: false },
  { key: 23, label: `合同税率(预留)`, visible: false },
  { key: 24, label: `备注`, visible: true },
  { key: 25, label: `激活标识`, visible: false },
  { key: 26, label: `删除标志`, visible: false },
  { key: 27, label: `创建部门`, visible: false },
  { key: 28, label: `创建人`, visible: false },
  { key: 29, label: `创建时间`, visible: false },
  { key: 30, label: `更新人`, visible: false },
  { key: 31, label: `更新时间`, visible: false },
  { key: 32, label: `终版合同`, visible: true },
  { key: 33, label: `客户合同编号`, visible: true },
  { key: 34, label: `海威SAP订单号`, visible: true },
  { key: 35, label: `海威合同归档编号`, visible: true },
  { key: 36, label: `软控SAP订单号`, visible: true },
  { key: 37, label: `软控SAP项目号`, visible: true },
  { key: 38, label: `合同负责人`, visible: true },
  { key: 39, label: `合同大写金额`, visible: false },
  { key: 40, label: `合同模板标识`, visible: true },
  { key: 41, label: `软控合同额（元）`, visible: true },
  { key: 42, label: `关联框架合同`, visible: true },
  { key: 43, label: `框架合同有效期`, visible: false },
  { key: 44, label: `合同属地标识`, visible: true },
  { key: 45, label: `合同属地国家/地区`, visible: true },
  { key: 46, label: `结算币种`, visible: true },
  { key: 47, label: `对人民币汇率`, visible: true }
]);

const data = reactive<{ queryParams: ContractInfoQuery }>({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    contractFlag: undefined,
    contractCode: undefined,
    customerContractCode: undefined,
    contractName: undefined,
    contractCategory: undefined,
    contractType: undefined,
    businessDirection: undefined,
    contractDeptId: undefined,
    contractDate: undefined,
    contractTerritorialFlag: undefined,
    contractTerritorialCountry: undefined,
    settlementCurrency: undefined,
    rmbExchangeRate: undefined,
    totalPrice: undefined,
    oneCustomerId: undefined,
    oneCustomerName: undefined,
    oneRepresent: undefined,
    oneDate: undefined,
    twoCustomerId: undefined,
    twoRepresent: undefined,
    twoDate: undefined,
    contractStatus: undefined,
    flowStatus: undefined,
    templateId: undefined,
    ossId: undefined,
    paymentMethod: undefined,
    signatureAppendix: undefined,
    taxRate: undefined,
    activeFlag: undefined,
    contractManagerId: undefined,
    capitalizedAmount: undefined,
    contractTemplateFlag: undefined,
    params: {}
  }
});

const { queryParams } = toRefs(data);

// 终版合同上传对话框状态
const uploadDialog = reactive({
  visible: false,
  loading: false,
  form: {
    contractId: undefined as any,
    contractDeptId: undefined as any,
    contractStatus: undefined as any,
    oss: undefined as any
  }
});

const copyDialog = reactive({
  visible: false,
  loading: false,
  sourceContractId: undefined as string | number | undefined,
  sourceLabel: '' as string,
  form: {
    contractCode: '' as string,
    contractName: '' as string,
    remark: '' as string
  }
});
const copyCodeGenerated = ref(false);
const copyFormRef = ref<ElFormInstance>();
const copyFormRules = {
  contractCode: [{ required: true, message: '合同编号不能为空', trigger: 'blur' }],
  contractName: [{ required: true, message: '合同名称不能为空', trigger: 'blur' }]
};

const maintainDialog = reactive({
  visible: false,
  loading: false,
  form: {
    contractId: undefined as any,
    contractName: undefined as string | undefined,
    contractCode: undefined as string | undefined,
    customerContractCode: undefined as string | undefined,
    internalContractCode: undefined as string | undefined,
    externalContractCode: undefined as string | undefined,
    orderContractCode: undefined as string | undefined,
    projectContractCode: undefined as string | undefined,
    mesnacContractPrice: undefined as number | undefined
  }
});
const maintainFormRef = ref<ElFormInstance>();
const uploadFormRef = ref<ElFormInstance>();

// 合同激活表单校验规则
const uploadFormRules = {
  contractDeptId: [{ required: true, message: '请选择部门', trigger: 'change' }],
  oss: [
    {
      required: true,
      validator: (_rule: any, value: any, callback: (err?: Error) => void) => {
        if (value === undefined || value === null || value === '' || (Array.isArray(value) && value.length === 0)) {
          callback(new Error('请上传签字合同附件'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ]
};

/** 查询部门信息下拉框结构 */
const deptInfoList = ref([]);
const getDeptInfoListSelect = async () => {
  const params = { deptCategory: '03' } as any;
  const res = await allListDept(params);
  deptInfoList.value = res.data;
};

/** 查询合同信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listContractInfo(queryParams.value);
  contractInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

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

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

/** 新增按钮操作 */
const handleAdd = (contractCategory?: string | number) => {
  proxy.$tab.closePage(route);
  router.push({
    path: '/contract/contractInfo/edit',
    query: {
      type: 'add',
      contractCategory: contractCategory as string
    }
  });
};

/** 修改按钮操作 */
const handleUpdate = (row?: ContractInfoVO) => {
  const _contractId = row?.contractId || ids.value[0];
  proxy.$tab.closePage(route);
  router.push({
    path: '/contract/contractInfo/edit',
    query: {
      id: _contractId,
      type: 'update'
    }
  });
};

/** 合同状态为可用（审批通过，contract_status=3）：可进入编辑修改并重新发起审批 */
const canReapproveAfterApproved = (row: ContractInfoVO) => {
  return String(row.contractStatus) === '3';
};

const handleReapprove = (row: ContractInfoVO) => {
  const _contractId = row?.contractId;
  if (!_contractId) return;
  proxy.$tab.closePage(route);
  router.push({
    path: '/contract/contractInfo/edit',
    query: {
      id: _contractId,
      type: 'reapprove'
    }
  });
};

const handleView = (row?: ContractInfoVO) => {
  const _contractId = row?.contractId;
  proxy.$tab.closePage(route);
  router.push({
    path: '/contract/contractInfo/edit',
    query: {
      id: _contractId,
      type: 'view'
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ContractInfoVO) => {
  const _contractIds = row?.contractId || ids.value;
  await proxy?.$modal.confirm('是否确认删除合同信息编号为"' + _contractIds + '"的数据项？').finally(() => (loading.value = false));
  await delContractInfo(_contractIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

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

const handleExportApprovalWord = async (row: ContractInfoVO) => {
  try {
    const res = await exportContractApprovalWord(row.contractId);
    const blob = new Blob([res as unknown as BlobPart], {
      type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `合同审批单_${row.contractCode || row.contractId}.docx`;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    proxy?.$modal.msgSuccess('审批单导出成功');
  } catch (error) {
    proxy?.$modal.msgError('审批单导出失败，请检查合同状态或模板配置');
  }
};

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

// 打开上传终版合同对话框
const openUploadFinalDialog = (row?: ContractInfoVO) => {
  const contractId = row?.contractId || ids.value[0];
  if (!contractId) return;
  uploadDialog.form.contractId = contractId;
  uploadDialog.form.contractDeptId = undefined as any;
  uploadDialog.form.oss = undefined as any;
  uploadDialog.form.contractStatus = '5';
  uploadDialog.visible = true;
  nextTick(() => uploadFormRef.value?.clearValidate());
};

const openCopyDialog = () => {
  if (selectedRows.value.length !== 1) {
    proxy?.$modal.msgWarning('请选择一条要复制的合同');
    return;
  }
  const row = selectedRows.value[0];
  copyDialog.sourceContractId = row.contractId;
  copyDialog.sourceLabel = `${row.contractCode || ''} ${row.contractName || ''}`.trim() || String(row.contractId);
  copyDialog.form.contractCode = '';
  copyDialog.form.contractName = '';
  copyDialog.form.remark = '';
  copyCodeGenerated.value = false;
  copyDialog.visible = true;
  nextTick(() => copyFormRef.value?.clearValidate());
};

const generateCopyContractCode = async () => {
  if (copyCodeGenerated.value) return;
  try {
    const res = await getRuleGenerateCode({ codeRuleCode: CodeRuleEnum.CONTRACT } as any);
    copyDialog.form.contractCode = res.msg;
    copyCodeGenerated.value = true;
    proxy?.$modal.msgSuccess('合同编号生成成功');
  } catch {
    proxy?.$modal.msgError('生成合同编号失败');
  }
};

const submitCopy = async () => {
  try {
    await copyFormRef.value?.validate();
  } catch {
    return;
  }
  if (!copyDialog.sourceContractId) return;
  copyDialog.loading = true;
  try {
    const copyBo: ContractInfoForm = {
      contractId: copyDialog.sourceContractId,
      contractCode: copyDialog.form.contractCode.trim(),
      contractName: copyDialog.form.contractName.trim(),
      remark: copyDialog.form.remark?.trim()
    };
    await copyContractInfo(copyBo);
    proxy?.$modal.msgSuccess('复制成功，新合同为暂存状态');
    copyDialog.visible = false;
    await getList();
  } finally {
    copyDialog.loading = false;
  }
};

const openMaintainDialog = () => {
  if (selectedRows.value.length !== 1) {
    proxy?.$modal.msgWarning('请选择一条数据进行维护');
    return;
  }
  const row = selectedRows.value[0];
  Object.assign(maintainDialog.form, {
    contractId: row.contractId as any,
    contractName: row.contractName,
    contractCode: row.contractCode,
    customerContractCode: row.customerContractCode,
    internalContractCode: (row as any).internalContractCode,
    externalContractCode: (row as any).externalContractCode,
    orderContractCode: (row as any).orderContractCode,
    projectContractCode: (row as any).projectContractCode,
    mesnacContractPrice: (row as any).mesnacContractPrice
  });
  maintainDialog.visible = true;
};

const submitMaintain = async () => {
  if (!maintainDialog.form.contractId) return;
  maintainDialog.loading = true;
  try {
    await updateContractInfo({
      contractId: maintainDialog.form.contractId,
      customerContractCode: maintainDialog.form.customerContractCode,
      internalContractCode: maintainDialog.form.internalContractCode,
      externalContractCode: maintainDialog.form.externalContractCode,
      orderContractCode: maintainDialog.form.orderContractCode,
      projectContractCode: maintainDialog.form.projectContractCode,
      mesnacContractPrice: maintainDialog.form.mesnacContractPrice
    } as any);
    proxy?.$modal.msgSuccess('维护成功');
    maintainDialog.visible = false;
    await getList();
  } finally {
    maintainDialog.loading = false;
  }
};

// 确认上传，保存签字合同附件
const confirmUploadFinal = async () => {
  try {
    await uploadFormRef.value?.validate();
  } catch {
    return;
  }
  const { contractId, contractDeptId, oss, contractStatus } = uploadDialog.form;
  const ossStr = oss as unknown as string | string[];
  const finalOss = Array.isArray(ossStr) ? ossStr.filter(Boolean).join(',') : String(ossStr ?? '').trim();
  uploadDialog.loading = true;
  try {
    await updateContractInfo({
      contractId,
      contractDeptId,
      contractStatus,
      signatureAppendix: finalOss || undefined
    } as any);
    proxy?.$modal.msgSuccess('合同已激活！');
    uploadDialog.visible = false;
    await getList();
  } finally {
    uploadDialog.loading = false;
  }
};

/** 解析终版合同附件 OSS ID 列表 */
const parseFinalContractOssIds = (ossIds: string | number | undefined): string[] => {
  if (ossIds === undefined || ossIds === null || ossIds === '') return [];
  return String(ossIds)
    .split(',')
    .map((id) => id.trim())
    .filter(Boolean);
};

const getFinalContractFileCount = (ossIds: string | number | undefined) => parseFinalContractOssIds(ossIds).length;

// 下载终版合同（支持多个附件）
const downloadFinalContract = (ossIds: string | number) => {
  const ids = parseFinalContractOssIds(ossIds);
  if (ids.length === 0) {
    proxy?.$modal.msgWarning('该合同暂无终版合同附件');
    return;
  }
  ids.forEach((id) => download.oss(id));
};

// 查看审批记录
const handleApprovalRecord = (row: ContractInfoVO) => {
  approvalRecordRef.value?.init(row.contractId);
};

// 查看合同
const contractView = (e) => {
  console.log(e);
  router.push({ path: '/contract/contractView', query: { templateId: e.templateId, contractId: e.contractId } });
};

/** 判断是否可以查看详情 */
const canViewDetail = (row: ContractInfoVO) => {
  return row.contractStatus !== '1';
};

/** 判断是否可以激活合同订单 */
const canActivateOrder = (row: ContractInfoVO) => {
  if (String(row.contractCategory) === '3') {
    return false;
  }
  // 合同大类是产品销售且合同状态为可用（3）
  if (row.contractStatus !== '3') {
    return false;
  }
  return true;
  // "合同大类(1市场实施 2产品销售）
  // return row.contractCategory === '2';
};

/** 判断是否可以激活合同订单上传终版合同附件 */
const showUploadButton = (row: ContractInfoVO) => {
  return !row.signatureAppendix && row.contractStatus === '3' && row.contractCategory === '1';
};

/** 订单激活按钮操作 */
const handleOrderActivate = (row?: ContractInfoVO) => {
  const _contractId = row?.contractId;
  proxy.$tab.closePage(route);
  router.push({
    path: '/contract/contractInfo/orderActivate',
    query: {
      contractId: _contractId,
      type: 'add'
    }
  });
};
</script>
