<template>
  <div>
    <el-dialog v-model="dialog.visible" :title="title" width="960px" top="8vh" append-to-body destroy-on-close>
      <el-row :gutter="20">
        <el-col :span="24">
          <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="90px">
                  <el-form-item label="合同编号" prop="contractCode">
                    <el-input v-model="queryParams.contractCode" placeholder="请输入合同编号" clearable style="width: 180px" @keyup.enter="handleQuery" />
                  </el-form-item>
                  <el-form-item label="合同名称" prop="contractName">
                    <el-input v-model="queryParams.contractName" placeholder="请输入合同名称" clearable style="width: 220px" @keyup.enter="handleQuery" />
                  </el-form-item>
                  <el-form-item label="合同状态" prop="contractStatus">
                    <el-select v-model="queryParams.contractStatus" placeholder="请选择合同状态" clearable style="width: 160px">
                      <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>
                    <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="hover">
            <vxe-table
              ref="tableRef"
              height="420px"
              border
              show-overflow
              :data="contractList"
              :loading="loading"
              :row-config="{ keyField: 'contractId', isHover: true }"
              :checkbox-config="{ reserve: true, trigger: 'row', highlight: true, showHeader: prop.multiple }"
              @checkbox-all="handleCheckboxAll"
              @checkbox-change="handleCheckboxChange"
            >
              <vxe-column type="checkbox" width="50" align="center" />
              <vxe-column type="seq" title="序号" width="55" align="center" />
              <vxe-column field="contractCode" title="合同编号" align="center" min-width="140" />
              <vxe-column field="contractName" title="合同名称" align="center" min-width="220" show-overflow />
              <vxe-column field="contractCategory" title="合同大类" align="center" width="100">
                <template #default="scope">
                  <dict-tag :options="contract_category" :value="scope.row.contractCategory" />
                </template>
              </vxe-column>
              <vxe-column field="businessDirection" title="业务方向" align="center" width="100">
                <template #default="scope">
                  <dict-tag :options="business_direction" :value="scope.row.businessDirection" />
                </template>
              </vxe-column>
              <vxe-column field="deptName" title="部门" align="center" width="120" />
              <vxe-column field="oneCustomerName" title="甲方公司" align="center" min-width="160" show-overflow />
              <vxe-column field="twoCustomerName" title="乙方公司" align="center" min-width="160" show-overflow />
              <vxe-column field="contractDate" title="合同签订日期" align="center" width="140" />
              <vxe-column field="totalPrice" title="合同总价" align="center" width="120" />
              <vxe-column field="contractStatus" title="合同状态" align="center" width="100">
                <template #default="scope">
                  <dict-tag :options="contract_status" :value="scope.row.contractStatus" />
                </template>
              </vxe-column>
              <vxe-column field="contractManagerName" title="合同负责人" align="center" width="120" />
            </vxe-table>

            <pagination
              v-show="total > 0"
              :total="total"
              v-model:page="queryParams.pageNum"
              v-model:limit="queryParams.pageSize"
              @pagination="pageList"
            />
          </el-card>
        </el-col>
      </el-row>

      <template #footer>
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { listContractInfo } from '@/api/oa/erp/contractInfo';
import type { ContractInfoQuery, ContractInfoVO } from '@/api/oa/erp/contractInfo/types';
import { getCurrentInstance, reactive, ref, watch, toRefs, nextTick } from 'vue';
import type { FormInstance } from 'element-plus';
import { VxeTableInstance } from 'vxe-table';

interface Props {
  /** 弹框标题 */
  title?: string;
  /** 是否多选 */
  multiple?: boolean;
  /** 状态合同 */
  contractStatus?: string | number;
  /** 激活标识 */
  activeFlag?: string | number;
}

const prop = withDefaults(defineProps<Props>(), {
  title: '选择合同',
  multiple: false,
  contractStatus: '5',
  activeFlag: '1'
});

const emit = defineEmits<{
  confirmCallBack: [ContractInfoVO[]];
}>();

const proxy = (getCurrentInstance()?.proxy || {}) as any;
const { contract_category, business_direction, contract_status } = toRefs<any>(
  proxy?.useDict('contract_category', 'business_direction', 'contract_status')
);

const dialog = reactive({ visible: false });
const title = prop.title;
const showSearch = ref(true);
const loading = ref(false);
const total = ref(0);
const contractList = ref<ContractInfoVO[]>([]);
const selectContractList = ref<ContractInfoVO[]>([]);

const queryFormRef = ref<FormInstance>();
const tableRef = ref<VxeTableInstance<ContractInfoVO>>();
const queryParams = reactive<ContractInfoQuery>({
  pageNum: 1,
  pageSize: 10,
  contractCode: undefined,
  contractName: undefined,
  contractStatus: String(prop.contractStatus) as any,
  activeFlag: String(prop.activeFlag) as any
});

const getList = async () => {
  loading.value = true;
  try {
    const res = await listContractInfo(queryParams);
    contractList.value = res.rows || [];
    total.value = res.total || 0;
  } finally {
    loading.value = false;
  }
};

const pageList = async () => {
  await getList();
  const rows = contractList.value.filter((item) =>
    selectContractList.value.some((c) => c.contractId === item.contractId)
  );
  await nextTick(() => tableRef.value?.setCheckboxRow(rows, true));
};

const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

const resetQuery = (refresh = true) => {
  queryFormRef.value?.resetFields();
  queryParams.contractStatus = String(prop.contractStatus) as any;
  queryParams.pageNum = 1;
  refresh && handleQuery();
};

const handleCheckboxChange = (checked: any) => {
  if (!prop.multiple && checked.checked) {
    tableRef.value?.setCheckboxRow(selectContractList.value, false);
    selectContractList.value = [];
  }
  const row = checked.row as ContractInfoVO;
  if (checked.checked) {
    selectContractList.value.push(row);
  } else {
    selectContractList.value = selectContractList.value.filter((item) => item.contractId !== row.contractId);
  }
};

const handleCheckboxAll = (checked: any) => {
  const rows = contractList.value;
  if (checked.checked) {
    rows.forEach((row) => {
      if (!selectContractList.value.some((item) => item.contractId === row.contractId)) {
        selectContractList.value.push(row);
      }
    });
  } else {
    selectContractList.value = selectContractList.value.filter(
      (item) => !rows.some((row) => row.contractId === item.contractId)
    );
  }
};

const confirm = () => {
  if (selectContractList.value.length === 0) {
    proxy?.$modal?.msgWarning?.('请先勾选合同');
    return;
  }
  emit('confirmCallBack', selectContractList.value);
  close();
};

const open = async () => {
  dialog.visible = true;
};

const close = () => {
  dialog.visible = false;
};

watch(
  () => dialog.visible,
  async (val) => {
    if (val) {
      selectContractList.value = [];
      queryParams.pageNum = 1;
      await getList();
    } else {
      tableRef.value?.clearCheckboxReserve?.();
      tableRef.value?.clearCheckboxRow?.();
      resetQuery(false);
      contractList.value = [];
      total.value = 0;
      selectContractList.value = [];
    }
  }
);

defineExpose({
  open,
  close
});
</script>

