<template>
  <div class="p-4 bg-gray-50 min-h-screen">
    <div class="max-w-4xl mx-auto">
      <!-- 顶部按钮区域 -->
      <el-card class="mb-4 rounded-lg shadow-sm bg-white border border-gray-100 transition-all hover:shadow-md">
        <approvalButton
          @submitForm="submitForm"
          @approvalVerifyOpen="approvalVerifyOpen"
          @handleApprovalRecord="handleApprovalRecord"
          :buttonLoading="buttonLoading"
          :id="form.id"
          :status="form.state"
          :pageType="routeParams.type"
        />
      </el-card>
      <!-- 表单区域 -->
      <el-card class="rounded-lg shadow-sm bg-white border border-gray-100 transition-all hover:shadow-md overflow-hidden">
        <div class="p-4 bg-gradient-to-r from-blue-50 to-indigo-50 border-b border-gray-100">
          <h3 class="text-lg font-semibold text-gray-800">专项方案信息</h3>
        </div>
        <div class="p-6">
          <el-form ref="leaveFormRef" v-loading="loading" disabled :model="form" :rules="rules" label-width="150px" class="space-y-4">
            <div class="">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="企业登记注册类型" prop="supplierType">
                    <el-select v-model="form.supplierType" placeholder="请选择供应商类型" @change="handleTypeChange">
                      <el-option label="劳务" value="劳务"></el-option>
                      <el-option label="技术服务" value="技术服务"></el-option>
                      <el-option label="物资设备" value="物资设备"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="企业名称" prop="supplierName">
                    <el-input v-model="form.supplierName" placeholder="请输入企业名称" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="企业法定代表人" prop="supplierPerson">
                    <el-input v-model="form.supplierPerson" placeholder="请输入法定代表人" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="统一社会信用代码" prop="supplierCode">
                    <el-input v-model="form.supplierCode" placeholder="请输入统一社会信用代码" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="企业注册地址" prop="supplierAddres">
                    <el-input v-model="form.supplierAddres" placeholder="请输入注册地址" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="负责人姓名" prop="personName">
                    <el-input v-model="form.personName" placeholder="请输入负责人姓名" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="负责人联系电话" prop="personPhone">
                    <el-input v-model="form.personPhone" placeholder="请输入联系电话" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="纳税规模" prop="taxScale">
                    <el-select v-model="form.taxScale" placeholder="请选择纳税规模">
                      <el-option label="一般纳税人" value="一般纳税人"></el-option>
                      <el-option label="小规模纳税人" value="小规模纳税人"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="开户行户名" prop="bankPersonName">
                    <el-input v-model="form.bankPersonName" placeholder="请输入开户行户名" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="开户银行" prop="bankName">
                    <el-input v-model="form.bankName" placeholder="请输入开户银行" clearable />
                  </el-form-item> </el-col
                ><el-col :span="12">
                  <el-form-item label="开户行账号" prop="bankAccount">
                    <el-input v-model="form.bankAccount" placeholder="请输入开户行账号" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="经营范围" prop="scope">
                    <el-input v-model="form.scope" placeholder="请输入经营范围" clearable />
                  </el-form-item> </el-col
                ><el-col :span="12">
                  <el-form-item label="企业资质等级" prop="supplierLivel">
                    <el-input v-model="form.supplierLivel" placeholder="请输入资质等级" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="发证日期" prop="issueDate">
                    <el-date-picker v-model="form.issueDate" type="date" placeholder="请选择发证日期" value-format="YYYY-MM-DD" />
                  </el-form-item> </el-col
                ><el-col :span="12">
                  <el-form-item label="证书有效期" prop="certificateValidity">
                    <el-date-picker v-model="form.certificateValidity" type="date" placeholder="请选择证书有效期" value-format="YYYY-MM-DD" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="近三年营业额" prop="pastThreeYears">
                    <el-input v-model="form.pastThreeYears" placeholder="请输入近三年营业额" clearable />
                  </el-form-item> </el-col
                ><el-col :span="12">
                  <el-form-item label="生产许可证编号" prop="safeCode">
                    <el-input v-model="form.safeCode" placeholder="请输入许可证编号" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="生产许可证发证日期" prop="safeCodeData">
                    <el-date-picker v-model="form.safeCodeData" type="date" placeholder="请选择发证日期" />
                  </el-form-item> </el-col
                ><el-col :span="12">
                  <el-form-item label="生产许可证发证日期" prop="safeCertificateValidity">
                    <el-date-picker v-model="form.safeCertificateValidity" type="date" placeholder="请选择发证日期" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row class="mb-4" v-if="form.supplierType === '劳务'">
                <el-col :span="12">
                  <el-form-item label="一建建造师" prop="build1">
                    <el-input v-model="form.build1" placeholder="请输入一建建造师数量" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="二建建造师" prop="build2">
                    <el-input v-model="form.build2" placeholder="请输入二建建造师数量" clearable />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="其他（分别写）" prop="build4">
                    <el-input v-model="form.build3" placeholder="请输入其他人员数量" clearable />
                  </el-form-item> </el-col
                ><el-col :span="12">
                  <el-form-item label="注册造价工程师" prop="build3">
                    <el-input v-model="form.build4" placeholder="请输入注册造价工程师数量" clearable />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="24" class="mb-4" v-if="form.supplierType === '劳务'">
                <el-col :span="12">
                  <el-form-item label="高级工程师人数" prop="personnelNumber1">
                    <el-input v-model="form.personnelNumber1" placeholder="请输高级工程师数量" clearable />
                  </el-form-item> </el-col
                ><el-col :span="12">
                  <el-form-item label="工程师数量" prop="personnelNumber2">
                    <el-input v-model="form.personnelNumber2" placeholder="请输入工程师数量" clearable />
                  </el-form-item> </el-col
                ><el-col :span="12">
                  <el-form-item label="助理工程师数量" prop="personnelNumber3">
                    <el-input v-model="form.personnelNumber3" placeholder="请输入助理工程师数量" clearable />
                  </el-form-item> </el-col
                ><el-col :span="12">
                  <el-form-item label="其他人员数量" prop="personnelNumber4">
                    <el-input v-model="form.personnelNumber4" placeholder="请输入其他人员数量" clearable />
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-form>
        </div>
      </el-card>
      <!-- 提交组件 -->
      <approvalRecord ref="approvalRecordRef"></approvalRecord>
      <submitVerify ref="submitVerifyRef" :task-variables="taskVariables" @submit-callback="submitCallback" />
      <!-- 流程选择对话框 -->
      <el-dialog
        draggable
        v-model="dialogVisible.visible"
        :title="dialogVisible.title"
        :before-close="handleClose"
        width="500"
        class="rounded-lg shadow-lg"
      >
        <div class="p-4">
          <p class="text-gray-600 mb-4">请选择要启动的流程：</p>
          <el-select v-model="flowCode" placeholder="请选择流程" style="width: 100%">
            <el-option v-for="item in flowCodeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
        <template #footer>
          <div class="dialog-footer p-4 border-t border-gray-100 flex justify-end space-x-3">
            <el-button @click="handleClose" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50 transition-colors"
              >取消</el-button
            >
            <el-button type="primary" @click="submitFlow()" class="px-4 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors"
              >确认</el-button
            >
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup name="Leave" lang="ts">
import { LeaveForm, LeaveQuery } from '@/api/workflow/leave/types';
import { startWorkFlow } from '@/api/workflow/task';
import SubmitVerify from '@/components/Process/submitVerify.vue';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';
import { StartProcessBo } from '@/api/workflow/workflowCommon/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
import { useUserStoreHook } from '@/store/modules/user';
import { getSupplierInput } from '@/api/supplierInput/supplierInput';

// 获取用户 store
const userStore = useUserStoreHook();
// 从 store 中获取项目列表和当前选中的项目
const currentProject = computed(() => userStore.selectedProject);
const buttonLoading = ref(false);
const loading = ref(true);
//路由参数
const routeParams = ref<Record<string, any>>({});
const flowCode = ref<string>('');
const status = ref<string>('');
const dialogVisible = reactive<DialogOption>({
  visible: false,
  title: '流程定义'
});
//提交组件
const submitVerifyRef = ref<InstanceType<typeof SubmitVerify>>();
//审批记录组件
const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();
const leaveFormRef = ref<ElFormInstance>();
const dialog = reactive({
  visible: false,
  title: '',
  isEdit: false
});
const submitFormData = ref<StartProcessBo>({
  businessId: '',
  flowCode: '',
  variables: {}
});
const taskVariables = ref<Record<string, any>>({});
const flowCodeOptions = [
  {
    value: currentProject.value?.id + '_supplierInput',
    label: '供应商入库审核'
  }
];
const initFormData = {
  id: undefined,
  supplierType: undefined,
  supplierName: undefined,
  supplierPerson: undefined,
  supplierCode: undefined,
  supplierAddres: undefined,
  personName: undefined,
  personPhone: undefined,
  bankPersonName: undefined,
  bankName: undefined,
  bankAccount: undefined,
  taxScale: undefined,
  scope: undefined,
  supplierLivel: undefined,
  issueDate: undefined,
  certificateValidity: undefined,
  pastThreeYears: undefined,
  safeCode: undefined,
  safeCodeData: undefined,
  safeCertificateValidity: undefined,
  registeredNumber: undefined, // 后端返回的拼接字符串（如“1,2,3,4”）
  personnelNumber: undefined, // 后端返回的拼接字符串（如“5,6,7,8”）
  fileId: undefined,
  inputFile: undefined,
  state: '0', // 新增默认待审核
  // 新增：用于表单输入的单独字段
  build1: undefined, // 一建建造师
  build2: undefined, // 二建建造师
  build3: undefined, // 注册造价工程师
  build4: undefined, // 其他注册人员
  personnelNumber1: undefined, // 高级工程师
  personnelNumber2: undefined, // 工程师
  personnelNumber3: undefined, // 助理工程师
  personnelNumber4: undefined // 其他职称人员
};
const data = reactive<PageData<LeaveForm, LeaveQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    projectId: currentProject.value?.id,
    fileName: undefined,
    fileType: undefined,
    fileSuffix: undefined,
    fileStatus: undefined,
    originalName: undefined,
    newest: undefined,
    params: {}
  },
  rules: {
    versionNumber: [{ required: true, message: '版本号不能为空', trigger: 'blur' }],
    fileName: [{ required: true, message: '文件名称不能为空', trigger: 'blur' }],
    fileType: [{ required: true, message: '文件类型不能为空', trigger: 'change' }],
    fileUrl: [
      {
        validator: (rule, value, callback) => {
          // 新增时必须上传文件
          if (!form.value.fileUrl) {
            callback(new Error('请上传图纸文件'));
          } else {
            callback();
          }
        },
        trigger: 'change'
      }
    ]
  }
});

const handleClose = () => {
  dialogVisible.visible = false;
  flowCode.value = '';
  buttonLoading.value = false;
};
const { form, rules } = toRefs(data);

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

/** 获取详情 */
const getInfo = () => {
  loading.value = true;
  buttonLoading.value = false;
  nextTick(async () => {
    const res = await getSupplierInput(routeParams.value.id);
    Object.assign(form.value, res.data);
    loading.value = false;
    buttonLoading.value = false;
  });
};
/** 提交按钮 */
const submitForm = (status1: string) => {
  status.value = status1;
  buttonLoading.value = true;
  dialog.visible = false;
  submit(status.value, form.value);
};
const submitFlow = async () => {
  handleStartWorkFlow(form.value);
  dialogVisible.visible = false;
};
//提交申请
const handleStartWorkFlow = async (data: LeaveForm) => {
  try {
    submitFormData.value.flowCode = flowCode.value;
    submitFormData.value.businessId = data.id;
    //流程变量
    taskVariables.value = {
      // leave4/5 使用的流程变量
      userList: ['1', '3', '4']
    };
    submitFormData.value.variables = taskVariables.value;
    const resp = await startWorkFlow(submitFormData.value);
    if (submitVerifyRef.value) {
      buttonLoading.value = false;
      submitVerifyRef.value.openDialog(resp.data.taskId);
    }
  } finally {
    buttonLoading.value = false;
  }
};
//审批记录
const handleApprovalRecord = () => {
  approvalRecordRef.value.init(form.value.id);
};
//提交回调
const submitCallback = async () => {
  await proxy.$tab.closePage(proxy.$route);
  proxy.$router.go(-1);
};
//审批
const approvalVerifyOpen = async () => {
  submitVerifyRef.value.openDialog(routeParams.value.taskId);
};
// 图纸上传成功之后 开始提交
const submit = async (status, data) => {
  form.value = data;
  if (status === 'draft') {
    buttonLoading.value = false;
    proxy?.$modal.msgSuccess('暂存成功');
    proxy.$tab.closePage(proxy.$route);
    proxy.$router.go(-1);
  } else {
    if ((form.value.state === 'draft' && (flowCode.value === '' || flowCode.value === null)) || routeParams.value.type === 'add') {
      flowCode.value = flowCodeOptions[0].value;
      dialogVisible.visible = true;
      return;
    }
    //说明启动过先随意穿个参数
    if (flowCode.value === '' || flowCode.value === null) {
      flowCode.value = 'xx';
    }
    console.log(data);
    await handleStartWorkFlow(data);
  }
};

onMounted(() => {
  nextTick(async () => {
    routeParams.value = proxy.$route.query;
    reset();
    loading.value = false;
    if (routeParams.value.type === 'update' || routeParams.value.type === 'view' || routeParams.value.type === 'approval') {
      getInfo();
    }
  });
});
</script>
<style scoped lang="scss">
/* 全局样式 */
:root {
  --primary: #409eff;
  --primary-light: #66b1ff;
  --primary-dark: #3a8ee6;
  --success: #67c23a;
  --warning: #e6a23c;
  --danger: #f56c6c;
  --info: #909399;
}

/* 表单样式优化 */
.el-form-item {
  .el-form-item__label {
    color: #606266;
    font-weight: 500;
  }

  .el-input__inner,
  .el-select .el-input__inner {
    border-radius: 4px;
    transition:
      border-color 0.2s,
      box-shadow 0.2s;

    &:focus {
      border-color: var(--primary-light);
      box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
    }
  }

  .el-textarea__inner {
    border-radius: 4px;
    transition:
      border-color 0.2s,
      box-shadow 0.2s;

    &:focus {
      border-color: var(--primary-light);
      box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
    }
  }
}

/* 按钮样式优化 */
.el-button {
  border-radius: 4px;
  transition: all 0.2s;

  &.is-primary {
    background-color: var(--primary);
    border-color: var(--primary);

    &:hover {
      background-color: var(--primary-light);
      border-color: var(--primary-light);
    }

    &:active {
      background-color: var(--primary-dark);
      border-color: var(--primary-dark);
    }
  }

  &.is-text {
    color: var(--primary);

    &:hover {
      color: var(--primary-light);
      background-color: rgba(64, 158, 255, 0.05);
    }
  }
}

/* 卡片样式优化 */
.el-card {
  transition: all 0.3s ease;

  &:hover {
    /* transform: translateY(-2px); */
  }
}

/* 对话框样式优化 */
.el-dialog {
  .el-dialog__header {
    background-color: #f5f7fa;
    border-bottom: 1px solid #ebeef5;
    padding: 15px 20px;
  }

  .el-dialog__title {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
  }

  .el-dialog__footer {
    padding: 15px 20px;
    border-top: 1px solid #ebeef5;
  }
}
</style>
