<template>
  <ContentWrap>

    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="130px"
      v-loading="formLoading"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="名称" prop="projectName">
            <el-input v-model="formData.projectName" disabled placeholder="请输入名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目类型" prop="projectType">
            <el-select v-model="formData.projectType" disabled placeholder="请选择项目类型">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.TTS_PROJECT_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="申请部门" prop="deptId">
            <el-tree-select
            disabled
            v-model="formData.deptId"
            :data="deptTree"
            :props="defaultProps"
            check-strictly
            node-key="id"
            placeholder=""
          />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="申请人" prop="userId">
            <el-select v-model="formData.userId" disabled placeholder="请选择申请人">
              <el-option
                v-for="dict in userOptions"
                :key="dict.id"
                :label="dict.nickname"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="测试完成日期" prop="testCompletionDate">
            <el-date-picker
            disabled
              v-model="formData.testCompletionDate"
              style="width: 100%"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="选择测试完成日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="申请上线日期" prop="onlineDate">
            <el-date-picker
              v-model="formData.onlineDate"
              style="width: 100%"
              disabled
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="选择申请上线日期"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="涉及第三方系统" prop="externalSystem">
            <el-radio-group v-model="formData.externalSystem" disabled>
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <OnlineApplicationList ref="onlineApplicationFormRef" :type="1" :onlineModuleInfo="formData.onlineModuleInfo" />
        </el-col>
        <el-col :span="24">
          <el-form-item label="上线注意事项" prop="precautions">
            <el-input type="textarea" disabled :rows="5" v-model="formData.precautions" placeholder="请输入上线注意事项" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="失败应急处理" prop="emergencyManagement">
            <el-input type="textarea" disabled :rows="5" v-model="formData.emergencyManagement" placeholder="请输入失败应急处理" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="申请人签字" prop="applicantSign">
            <div  class="signature-preview">
              <el-image class="image" v-if="formData.applicantSign" :src="formData.applicantSign" alt="签名预览" />
            </div>
          </el-form-item>
        </el-col>
      </el-row>
          <el-form-item v-if="visible" >
            <div>
              <HandleSign @success="setSign" @close="visible = false" />
            </div>
          </el-form-item>

      <!-- <el-form-item label="工作流编号" prop="processInstanceId">
        <el-input v-model="formData.processInstanceId" placeholder="请输入工作流编号" />
      </el-form-item>
      <el-form-item label="审批状态" prop="auditStatus">
        <el-radio-group v-model="formData.auditStatus">
          <el-radio value="1">请选择字典生成</el-radio>
        </el-radio-group>
      </el-form-item> -->
    </el-form>
    
  </ContentWrap>

</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { OnlineApplicationApi, OnlineApplicationVO } from '@/api/task/online'
import HandleSign from './HandleSign.vue'
import OnlineApplicationList from './components/index.vue'
import { defaultProps, handleTree } from '@/utils/tree'
import * as DeptApi from '@/api/system/dept'
import { propTypes } from '@/utils/propTypes'
import * as UserApi from '@/api/system/user'
/** 上线申请 表单 */
defineOptions({ name: 'OnlineApplicationForm' })
const { proxy }: any = getCurrentInstance();

const userOptions = ref<UserApi.UserVO[]>([]) // 用户列表
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const deptTree = ref() // 部门树形结构
const props = defineProps({
  id: propTypes.number.def(undefined),
  type: propTypes.number.def(undefined),
})
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const visible = ref(false)
const onlineApplicationFormRef = ref('')
const formData = ref({
  id: undefined,
  projectName: undefined,
  projectType: undefined,
  deptId: undefined,
  userId: undefined,
  testCompletionDate: undefined,
  onlineDate: undefined,
  externalSystem: undefined,
  precautions: undefined,
  emergencyManagement: undefined,
  applicantSign: undefined,
  processInstanceId: undefined,
  auditStatus: undefined
})
const formRules = reactive({
  projectName: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
  projectType: [{ required: true, message: '项目类型不能为空', trigger: 'change' }],
  deptId: [{ required: true, message: '申请部门不能为空', trigger: 'blur' }],
  userId: [{ required: true, message: '申请人不能为空', trigger: 'blur' }],
  testCompletionDate: [{ required: true, message: '测试完成日期不能为空', trigger: 'blur' }],
  onlineDate: [{ required: true, message: '申请上线日期不能为空', trigger: 'blur' }],
  externalSystem: [{ required: true, message: '上线系统是否涉及第三方系统不能为空', trigger: 'blur' }],
  precautions: [{ required: true, message: '上线注意事项不能为空', trigger: 'blur' }],
  emergencyManagement: [{ required: true, message: '失败应急处理不能为空', trigger: 'blur' }],
  applicantSign: [{ required: true, message: '申请人签字不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (id?: number) => {
  dialogVisible.value = true
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await OnlineApplicationApi.getOnlineApplication(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗


const setSign = (val) => {
  console.log('%csrc/views/task/online/OnlineApplicationForm.vue:143 val', 'color: #007acc;', val);
  formData.value.applicantSign = val
  visible.value = false
}
/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as OnlineApplicationVO
    // await onlineApplicationFormRef.value.validate()
    console.log('%csrc/views/task/online/OnlineApplicationForm.vue:214 onlineApplicationFormRef.value.getData()', 'color: #007acc;', onlineApplicationFormRef.value.getData());
    data.onlineModuleInfo = onlineApplicationFormRef.value.getData()
    if (!formType.value) {
      await OnlineApplicationApi.createOnlineApplication(data)
      message.success(t('common.createSuccess'))
    } else {
      await OnlineApplicationApi.updateOnlineApplication(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    goBack()

    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

const goBack = ()=> {
  proxy.$router.go(-1)
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    projectName: undefined,
    projectType: undefined,
    deptId: undefined,
    userId: undefined,
    testCompletionDate: undefined,
    onlineDate: undefined,
    externalSystem: undefined,
    precautions: undefined,
    emergencyManagement: undefined,
    applicantSign: undefined,
    processInstanceId: undefined,
    auditStatus: undefined
  }
  formRef.value?.resetFields()
}
const route = useRoute();
onMounted(async()=> {
  formType.value = props.id || route.query.id

  if (formType.value) await open(formType.value)

  deptTree.value = handleTree(await DeptApi.getSimpleDeptList())
   // 获得用户列表
  userOptions.value = await UserApi.getSimpleUserList()
})
</script>

<style scoped>
.signature-preview {
  display: flex;
  flex-direction: column;
}
.image {
  width: 200px;
  margin-top: 5px;
}
</style>