<template>
  <div class='p-2'>
    <el-card shadow='never'>
      <div style='display: flex; justify-content: space-between'>
        <div>
          <el-button v-if='submitButtonShow' :loading='buttonLoading' type='info' @click="submitForm('draft')">暂存
          </el-button>
          <el-button v-if='submitButtonShow' :loading='buttonLoading' type='primary' @click="submitForm('submit')">提
            交
          </el-button>
          <el-button v-if='approvalButtonShow' :loading='buttonLoading' type='primary' @click='approvalVerifyOpen'>
            审批
          </el-button>
          <el-button v-if="form && form.maintInstanceId !== null && form.status !== 'draft'" type='primary'
                     @click='handleApprovalRecord'>
            流程进度
          </el-button>
        </div>
        <div>
          <el-button style='float: right' @click='goBack()'>返回</el-button>
        </div>
      </div>
    </el-card>
    <el-card shadow='never' style='height: 78vh; overflow-y: auto'>
      <el-form ref='dmsBillsMaintInstanceFormRef' v-loading='loading' :disabled="routeParams.type === 'view'"
               :model='form' :rules='rules' label-width='120px'>
        <el-row :gutter='20'>
          <el-col :span='12'>
            <el-form-item label='保养计划' prop='planMaintId'>
              <!--          <el-input v-model="form.planMaintId" placeholder="请输入保养计划" />-->
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label='保养单号' prop='billsMaintCode'>
              <el-input v-model='form.billsMaintCode' placeholder='请输入保养单号' />
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label='保养组别' prop='maintGroup'>
              <el-input v-model='form.maintGroup' placeholder='请输入保养组别' />
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label='保养负责人' prop='maintSupervisor'>
              <el-input v-model='form.maintSupervisor' placeholder='请输入保养负责人' />
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label='保养级别' prop='maintLevel'>
              <el-select v-model='form.maintLevel' placeholder='请选择保养级别' style='width: 100%'>
                <el-option
                  v-for='dict in maint_level'
                  :key='dict.value'
                  :label='dict.label'
                  :value='dict.value'
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label='保养状态' prop='maintStatus'>
              <el-select v-model='form.maintStatus' placeholder='请选择保养状态' style='width: 100%' disabled>
                <el-option
                  v-for='dict in maint_status'
                  :key='dict.value'
                  :label='dict.label'
                  :value='dict.value'
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label='计划保养时间' prop='planBeginTime'>
              <el-date-picker clearable
                              v-model='form.planBeginTime'
                              type='datetime'
                              value-format='YYYY-MM-DD HH:mm:ss'
                              placeholder='请选择计划保养时间'
                              style='width: 100%'>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label='计划完成时间' prop='planEndTime'>
              <el-date-picker clearable
                              v-model='form.planEndTime'
                              type='datetime'
                              value-format='YYYY-MM-DD HH:mm:ss'
                              placeholder='请选择计划完成时间'
                              style='width: 100%'>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label='实际开始时间' prop='realBeginTime'>
              <el-date-picker clearable
                              v-model='form.realBeginTime'
                              type='datetime'
                              value-format='YYYY-MM-DD HH:mm:ss'
                              placeholder='请选择实际开始时间'
                              style='width: 100%'>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label='实际完成时间' prop='realEndTime'>
              <el-date-picker clearable
                              v-model='form.realEndTime'
                              type='datetime'
                              value-format='YYYY-MM-DD HH:mm:ss'
                              placeholder='请选择实际完成时间'
                              style='width: 100%'>
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label='保养完成率' prop='maintCompRate'>
              <el-input-number v-model='form.maintCompRate' :min='0' :max='100' :precision='2' :step='1' />
            </el-form-item>
          </el-col>
          <el-col :span='12'>
            <el-form-item label='流程状态' prop='status'>
              <el-select v-model='form.status' placeholder='请选择流程状态' disabled>
                <el-option
                  v-for='dict in status_dict'
                  :key='dict.value'
                  :label='dict.label'
                  :value='dict.value'
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span='24'>
            <el-form-item label='备注' prop='remark'>
              <el-input v-model='form.remark' type='textarea' :rows='3' placeholder='请输入备注' />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <!-- 提交组件 -->
    <submitVerify ref='submitVerifyRef' :task-variables='taskVariables' @submit-callback='submitCallback' />
    <!-- 审批记录 -->
    <approvalRecord ref='approvalRecordRef' />
    <el-dialog v-model='dialogVisible.visible' :title='dialogVisible.title' :before-close='handleClose' width='500'>
      <el-select v-model='flowCode' placeholder='Select' style='width: 240px'>
        <el-option v-for='item in flowCodeOptions' :key='item.value' :label='item.label' :value='item.value' />
      </el-select>
      <template #footer>
        <div class='dialog-footer'>
          <el-button @click='handleClose'>取消</el-button>
          <el-button type='primary' @click='submitFlow()'> 确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name='MaintEdit' lang='ts'>
import { startWorkFlow } from '@/api/workflow/task';
import SubmitVerify from '@/components/Process/submitVerify.vue';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';
import { AxiosResponse } from 'axios';
import { StartProcessBo } from '@/api/workflow/workflowCommon/types';
import {
  DmsBillsMaintInstanceForm,
  DmsBillsMaintInstanceQuery,
  DmsBillsMaintInstanceVO
} from '@/api/dms/dmsBillsMaintInstance/types';
import {
  getDmsBillsMaintInstance,
  addDmsBillsMaintInstance,
  updateDmsBillsMaintInstance
} from '@/api/dms/dmsBillsMaintInstance';
import { ElMessage } from 'element-plus';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const buttonLoading = ref(false);
const loading = ref(true);
//路由参数
const routeParams = ref<Record<string, any>>({});

const flowCodeOptions = [
  {
    value: 'planmaint',
    label: '保养工单申请'
  }
];

const flowCode = ref<string>('');

const dialogVisible = reactive<DialogOption>({
  visible: false,
  title: '流程定义'
});
//提交组件
const submitVerifyRef = ref<InstanceType<typeof SubmitVerify>>();
//审批记录组件
const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();

const dmsBillsMaintInstanceFormRef = ref<ElFormInstance>();

const submitFormData = ref<StartProcessBo>({
  businessId: '',
  flowCode: '',
  variables: {}
});
const taskVariables = ref<Record<string, any>>({});

const initFormData: DmsBillsMaintInstanceForm = {
  maintInstanceId: undefined,
  planMaintId: undefined,
  wfDefinitionId: undefined,
  billsMaintCode: '',
  maintGroup: '',
  maintSupervisor: '',
  maintLevel: '',
  planBeginTime: '',
  realBeginTime: '',
  planEndTime: '',
  realEndTime: '',
  maintStatus: '1',
  maintCompRate: 0,
  remark: '',
  status: 'waiting'
};
const data = reactive<PageData<DmsBillsMaintInstanceForm, DmsBillsMaintInstanceQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10
  },
  rules: {
    billsMaintCode: [
      { required: true, message: '保养单号不能为空', trigger: 'blur' }
    ]
  }
});

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

/** 表单重置 */
const reset = () => {
  if (!dmsBillsMaintInstanceFormRef.value) return;
  dmsBillsMaintInstanceFormRef.value.resetFields();
  Object.assign(form, initFormData);
};

/** 获取详情 */
const getInfo = async (id: string | number) => {
  try {
    const res = await getDmsBillsMaintInstance(id);
    form.value = { ...res.data };
  } catch (error) {
    console.error('获取保养工单详情失败:', error);
  }
};

/** 提交按钮 */
const submitForm = (status: string) => {
  try {
    dmsBillsMaintInstanceFormRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        buttonLoading.value = true;
        let res: AxiosResponse<DmsBillsMaintInstanceVO>;
        if (form.value.maintInstanceId) {
          res = await updateDmsBillsMaintInstance(form.value);
        } else {
          res = await addDmsBillsMaintInstance(form.value);
        }
        form.value = res.data;
        if (status === 'draft') {
          buttonLoading.value = false;
          proxy?.$modal.msgSuccess('暂存成功');
          proxy.$tab.closePage(proxy.$route);
          proxy.$router.go(-1);
        } else {
          if ((form.value.status === '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';
          }
          await handleStartWorkFlow(res.data);
        }
      }
    });
  } finally {
    buttonLoading.value = false;
  }
};

const submitFlow = async () => {
  handleStartWorkFlow(form.value);
  dialogVisible.visible = false;
};
//提交申请
const handleStartWorkFlow = async (data: DmsBillsMaintInstanceForm) => {
  try {
    submitFormData.value.flowCode = flowCode.value;
    submitFormData.value.businessId = data.maintInstanceId;
    //流程变量
    taskVariables.value = {
      data: data
    };
    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.maintInstanceId);
};
//提交回调
const submitCallback = async () => {
  await proxy.$tab.closePage(proxy.$route);
  proxy.$router.go(-1);
};

//返回
const goBack = () => {
  proxy.$tab.closePage(proxy.$route);
  proxy.$router.go(-1);
};
//审批
const approvalVerifyOpen = async () => {
  submitVerifyRef.value.openDialog(routeParams.value.taskId);
};
//校验提交按钮是否显示
const submitButtonShow = computed(() => {
  return (
    routeParams.value.type === 'add' ||
    (routeParams.value.type === 'update' &&
      form.value.status &&
      (form.value.status === 'draft' || form.value.status === 'cancel' || form.value.status === 'back'))
  );
});

//校验审批按钮是否显示
const approvalButtonShow = computed(() => {
  return routeParams.value.type === 'approval' && form.value.status && form.value.status === 'waiting';
});

// 保养级别字典
const maint_level = ref([
  { value: '1', label: '日常保养' },
  { value: '2', label: '月度保养' },
  { value: '3', label: '年度保养' }
]);

// 保养状态字典
const maint_status = ref([
  { value: '1', label: '待保养' },
  { value: '2', label: '保养中' },
  { value: '3', label: '已完成' }
]);

// 状态字典
const status_dict = ref([
  { value: 'draft', label: '草稿' },
  { value: 'waiting', label: '待处理' },
  { value: 'processing', label: '处理中' },
  { value: 'completed', label: '已完成' },
  { value: 'cancel', label: '已取消' },
  { value: 'back', label: '已退回' }
]);

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(routeParams.value.id);
    }
  });
});
</script>
