<template>
  <ProcessLayout class="wrap" v-if="showVisible" @click.stop="">
    <template #title> {{ t('审批流程') }}【{{ data.item.name }}】 </template>
    <template #close>
      <a-button type="primary" class="clean-icon" @click.stop="close">{{ t('关闭') }}</a-button>
    </template>
    <template #left>
      <FlowPanel
        :xml="data.xml"
        :taskRecords="data.taskRecords"
        :predecessorTasks="selectedPredecessorTasks"
        :processId="props.processId"
        position="top"
      >
        <FormInformation
          :opinionsComponents="data.opinionsComponents"
          :opinions="data.opinions"
          :disabled="false"
          :formInfos="data.formInfos"
          :formAssignmentData="data.formAssignmentData"
          ref="formInformation"
        />
      </FlowPanel>
    </template>
    <template #right>
      <a-tabs style="width: 280px">
        <a-tab-pane key="1" :tab="t('审批信息')">
          <NodeHead :nodeName="t('基础信息')" />
          <div class="description-box">
            <ProcessInfo class="item-box" :item="data.item">
              <NodeHead :nodeName="t('审批信息')" />
              <div
                class="text-box"
                v-if="approvalData.buttonConfigs && approvalData.buttonConfigs.length > 0"
              >
                <div class="text-label">{{ t('审批结果：') }}</div>
                <span>
                  <a-radio-group
                    v-model:value="approvalData.approvedType"
                    name="approvedType"
                    @change="changeApprovedType"
                  >
                    <span v-for="(item, index) in approvalData.buttonConfigs" :key="index">
                      <a-radio
                        v-if="item.approveType !== ApproveType.OTHER"
                        :value="item.approveType"
                        >{{ item.buttonName }}</a-radio
                      >
                    </span>
                  </a-radio-group>
                  <a-radio-group v-model:value="approvalData.approvedResult" name="buttonCode">
                    <span v-for="(item, index) in approvalData.buttonConfigs" :key="index">
                      <a-radio
                        v-if="item.approveType === ApproveType.OTHER"
                        :value="item.buttonCode"
                        @change="changeButtonCodeType"
                        >{{ item.buttonName }}</a-radio
                      >
                    </span>
                  </a-radio-group></span
                >
              </div>
              <div class="text-box" v-if="approvalData.approvedType === ApproveType.REJECT">
                <div class="text-label">{{ t('驳回节点：') }}</div>
                <a-select style="width: 100%" v-model:value="approvalData.rejectNodeActivityId">
                  <a-select-option
                    v-for="(item, index) in approvalData.rejectNodeActivityIds"
                    :key="index"
                    :value="item.activityId"
                    >{{ item.activityName }}</a-select-option
                  >
                </a-select>
              </div>
              <div class="text-box">
                <div class="text-label">{{ t('审批内容：') }}</div>
                <a-textarea
                  v-model:value="approvalData.approvedContent"
                  :rows="6"
                  :maxlength="100"
                />
              </div>
            </ProcessInfo>
          </div>
          <!-- 电子签章 -->
          <a-form-item :label="t('电子签章')" name="password" v-if="data.hasStamp">
            <SelectStamp v-if="data.hasStamp" v-model:stampId="approvalData.stampInfo.stampId" />
          </a-form-item>
          <a-form-item :label="t('签章密码')" name="password" v-if="data.hasStampPassword">
            <a-input-password v-model:value="approvalData.stampInfo.password" style="width: 100%" />
          </a-form-item>

          <ApproveUser
            v-if="approveUserData.visible"
            :taskList="approveUserData.list"
            :schemaId="approveUserData.schemaId"
            @change="changeApproveUserData" />
          <div class="button-box">
            <a-button type="primary" class="mr-2" :loading="data.submitLoading" @click="submit">{{
              t('审批')
            }}</a-button>
            <!-- 转办 -->
            <TransferUser :taskId="props.taskId" @close="close" />
            <!-- 加签减签 -->
            <AddOrSubtract
              v-if="approvalData.isAddOrSubSign"
              :schemaId="props.schemaId"
              :taskId="props.taskId"
            /> </div
        ></a-tab-pane>
        <a-tab-pane key="2" :tab="t('传阅信息')" force-render>
          <MemberTable v-model:memberList="approvalData.circulateConfigs" :isCommonType="true" />
        </a-tab-pane>
      </a-tabs>
    </template>
  </ProcessLayout>
</template>

<script setup lang="ts">
  import { computed, reactive, ref, defineAsyncComponent, onMounted } from 'vue';
  import ProcessLayout from './flow/Layout.vue';
  import FormInformation from './flow/FormInformation.vue';
  import FlowPanel from './flow/FlowPanel.vue';
  import ProcessInfo from './flow/ProcessInfo.vue';
  import { NodeHead } from '/@/components/ModalPanel/index';
  import { getApprovalProcess, getRejectNode, postApproval } from '/@/api/workflow/task';
  import userTaskItem from './../hooks/userTaskItem';
  import { ApproveTask, PostApprovalData, rejectNodeItem } from '/@/model/workflow/bpmnConfig';
  import { ButtonConfigItem } from '/@/model/workflow/workflowConfig';
  import { MemberConfig } from '/@/model/workflow/memberSetting';
  import { ApproveCode, ApproveType } from '/@/enums/workflowEnum';
  import { separator } from '../../design/bpmn/config/info';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const ApproveUser = defineAsyncComponent(() => import('./flow/ApproveUser.vue'));
  const AddOrSubtract = defineAsyncComponent(() => import('./flow/AddOrSubtract.vue'));
  const TransferUser = defineAsyncComponent(() => import('./flow/TransferUser.vue'));
  const MemberTable = defineAsyncComponent(
    () => import('/@bpmn/components/member/MemberTable.vue'),
  );
  const SelectStamp = defineAsyncComponent(() => import('./stamp/SelectStamp.vue'));
  const props = withDefaults(
    defineProps<{
      schemaId: string;
      processId: string;
      taskId: string;
      visible: boolean;
    }>(),
    {
      schemaId: '',
      processId: '',
      taskId: '',
      visible: false,
    },
  );
  let emits = defineEmits(['close']);

  let formInformation = ref();
  let showVisible = ref(false);
  let showLoading = ref(false);
  let approvalData: {
    isAddOrSubSign: Boolean; //是否加签减签
    stampInfo: {
      stampId: string;
      password: string;
    };
    buttonConfigs: Array<ButtonConfigItem>;
    approvedType: ApproveType;
    approvedContent: string;
    approvedResult: string;
    rejectNodeActivityId: string;
    rejectNodeActivityIds: Array<rejectNodeItem>;
    circulateConfigs: Array<MemberConfig>;
  } = reactive({
    isAddOrSubSign: false,
    stampInfo: {
      stampId: '',
      password: '',
    },
    buttonConfigs: [],
    approvedType: ApproveType.AGREE,
    approvedResult: ApproveCode.AGREE,
    approvedContent: '',
    rejectNodeActivityId: '',
    rejectNodeActivityIds: [],
    circulateConfigs: [],
  });
  const { data, approveUserData, initProcessData, notificationError, notificationSuccess } =
    userTaskItem();

  onMounted(() => {
    if (props.visible) {
      approval();
    }
  });
  const selectedPredecessorTasks = computed(() => {
    return data.predecessorTasks.filter((ele) => {
      return ele.taskId;
    });
  });

  // 审批
  async function approval() {
    showLoading.value = true;
    reset();
    if (props.taskId) {
      try {
        let res = await getApprovalProcess(props.taskId, props.processId);
        initProcessData(res);
        if (res.buttonConfigs) {
          approvalData.buttonConfigs = res.buttonConfigs;
        }
        if (res.relationTasks) {
          data.predecessorTasks = res.relationTasks;
        }
        if (res.isAddOrSubSign) {
          approvalData.isAddOrSubSign = res.isAddOrSubSign;
        }

        approvalData.approvedType = ApproveType.AGREE;
        approvalData.approvedContent = '';
        approvalData.rejectNodeActivityId = '';
        approvalData.rejectNodeActivityIds = [];
        approvalData.circulateConfigs = [];
        showLoading.value = false;
        showVisible.value = true;
      } catch (error) {
        showLoading.value = false;
        emits('close');
      }
    } else {
      // 只能选一个
      showLoading.value = false;
      showVisible.value = false;
    }
  }

  async function changeApprovedType() {
    if (approvalData.approvedType == ApproveType.AGREE) {
      approvalData.approvedResult = ApproveCode.AGREE;
    } else if (approvalData.approvedType == ApproveType.REJECT) {
      approvalData.rejectNodeActivityIds = await getRejectNode(props.processId, props.taskId);
      approvalData.approvedResult = ApproveCode.REJECT;
    } else if (approvalData.approvedType == ApproveType.DISAGREE) {
      approvalData.approvedResult = ApproveCode.DISAGREE;
    } else if (approvalData.approvedType == ApproveType.FINISH) {
      approvalData.approvedResult = ApproveCode.FINISH;
    } else {
      approvalData.approvedResult = '';
    }
  }
  function changeButtonCodeType() {
    approvalData.approvedType = ApproveType.OTHER;
  }
  function getUploadFileFolderIds(formModels) {
    let fileFolderIds: Array<string> = [];
    let uploadComponentIds = formInformation.value.getUploadComponentIds();
    uploadComponentIds.forEach((ids) => {
      if (ids.includes(separator)) {
        let arr = ids.split(separator);
        if (arr.length == 2 && formModels[arr[0]][arr[1]]) {
          fileFolderIds.push(formModels[arr[0]][arr[1]]);
        }
      }
    });
    return fileFolderIds;
  }
  async function submit() {
    data.submitLoading = true;
    try {
      let validateForms = await formInformation.value.validateForm();
      if (validateForms.length > 0) {
        let successValidate = validateForms.filter((ele) => {
          return ele.validate;
        });
        if (successValidate.length == validateForms.length) {
          let formModels = await formInformation.value.getFormModels();
          let fileFolderIds: Array<string> = getUploadFileFolderIds(formModels);
          let params: PostApprovalData = {
            approvedType: approvalData.approvedResult
              ? ApproveType.OTHER
              : approvalData.approvedType,
            approvedResult: approvalData.approvedResult, // approvalData.approvedType 审批结果 如果为 4 就需要传buttonCode
            approvedContent: approvalData.approvedContent,
            formData: formModels,
            rejectNodeActivityId: approvalData.rejectNodeActivityId,
            taskId: props.taskId,
            fileFolderIds,
            circulateConfigs: approvalData.circulateConfigs,
            stampId: approvalData.stampInfo.stampId,
            stampPassword: approvalData.stampInfo.password,
          };
          let res = await postApproval(params);
          // 下一节点审批人
          let taskList: Array<ApproveTask> = [];
          if (res && res.length > 0) {
            taskList = res
              .filter((ele) => {
                return ele.isMultiInstance == false && ele.isAppoint == true;
              })
              .map((ele) => {
                return {
                  taskId: ele.taskId,
                  taskName: ele.taskName,
                  provisionalApprover: ele.provisionalApprover,
                  selectIds: [],
                };
              });
            if (taskList.length > 0) {
              approveUserData.list = taskList;
              approveUserData.schemaId = props.schemaId;
              approveUserData.visible = true;
              data.submitLoading = false;
            } else {
              close();
              data.submitLoading = false;
              save(true, t('审批流程'));
            }
          } else {
            close();
            data.submitLoading = false;
            save(true, t('审批流程'));
          }
        } else {
          data.submitLoading = false;
          notificationError(t('审批流程'), t('表单校验未通过'));
        }
      }
    } catch (error) {
      data.submitLoading = false;
      notificationError(t('审批流程'), t('审批流程失败'));
    }
  }

  function changeApproveUserData() {
    approveUserData.visible = false;
    close();
  }
  function save(res: boolean, title: string) {
    if (res) {
      notificationSuccess(title);
      close();
    } else {
      notificationError(title);
    }
  }
  function close() {
    showVisible.value = false;
    emits('close');
  }
  function reset() {
    approvalData.isAddOrSubSign = false;
    approvalData.stampInfo = {
      stampId: '',
      password: '',
    };
    approvalData.buttonConfigs = [];
    approvalData.approvedType = ApproveType.AGREE;
    approvalData.approvedContent = '';
    approvalData.rejectNodeActivityId = '';
    approvalData.rejectNodeActivityIds = [];
    approvalData.circulateConfigs = [];
  }
</script>
<style lang="less" scoped>
  .description-box {
    display: flex;
    flex-direction: column;
    padding-top: 10px;
    align-items: center;
    justify-content: center;
    color: rgb(102 102 102 / 99.6%);
    margin-bottom: 20px;

    .title {
      align-self: flex-start;
      margin-bottom: 20px;
    }

    .item-box {
      align-self: flex-start;
    }

    .text-box {
      display: flex;
      margin: 10px 0;

      .text-label {
        width: 80px;
        height: 40px;
        display: inline-flex;
        justify-content: flex-end;
        margin-right: 4px;
      }
    }
  }
  // 传阅人
  :deep(.opr-box) {
    flex-direction: column !important;

    .header-box {
      flex-basis: 40px !important;
    }

    .button-box {
      flex-direction: row !important;
    }
  }
</style>
