<template>
  <div class="guns-layout-content">
    <div class="guns-layout">
      <div class="guns-layout-content-application">
        <div class="content-mian">
          <div class="content-header">
            <div class="back" @click="back"><LeftOutlined class="back-icon" /> 返回</div>
            <a-space>
              <a-button class="border-radius" type="primary" @click="submit()" v-if="showSubmit">{{ submitAliasName }}</a-button>
              <a-button class="border-radius" @click="save" v-if="showSave">{{ saveAliasName }}</a-button>
              <a-button class="border-radius" @click="copyTo" v-if="showCopyTo"
                >{{ copyToAliasName }} <span v-if="copyToUserList?.length">（{{ copyToUserList?.length }}）</span></a-button
              >
            </a-space>
          </div>
          <div class="content-mian-body">
            <a-spin :delay="100" :spinning="loading" style="overflow-y: auto" v-if="tabsActiveKey == '1'">
              <WorkFlowForm
                :definitionId="definitionId"
                v-if="definitionId"
                ref="workFlowFormRef"
                :draft="props.draft"
                :draftId="props.draftId"
              />
            </a-spin>
            <FlowView :definitionId="definitionId" v-if="tabsActiveKey == '2'" />
          </div>
        </div>
      </div>
    </div>

    <!-- 流程预测 -->
    <FlowPrediction v-model:visible="showFlowPrediction" v-if="showFlowPrediction" @done="submit" :params="flowPredictionParams" />
    <!-- 添加抄送人 -->
    <FlowAddCopyUser v-model:visible="showFlowCopy" v-if="showFlowCopy" @done="closeAddCopyUser" :copyToUserList="copyToUserList" />
  </div>
</template>

<script setup name="WorkflowTaskStart">
import { useRoute, useRouter } from 'vue-router';
import { onMounted, ref, computed, watch } from 'vue';
import { useGeneratorStore } from '@/store/modules/generator';
import FlowView from './components/flow-view.vue';
import WorkFlowForm from './components/flow-form.vue';
import { FlowStartApi } from './api/FlowStartApi';
import { message } from 'ant-design-vue/es';
import FlowPrediction from './components/flow-prediction.vue';
import FlowAddCopyUser from './components/flow-add-copy-user.vue';

defineOptions({
  name: 'WorkflowTaskStart'
})

const props = defineProps({
  definitionId: {
    type: String,
    default: ''
  },
  // 是否是草稿
  draft: {
    type: Boolean,
    default: false
  },
  // 草稿id
  draftId: {
    type: String,
    default: ''
  }
});

const emits = defineEmits(['closeDraft']);

const generatorStore = useGeneratorStore();
// tab选中
const flowStartActiveTab = computed(() => generatorStore.flowStartActiveTab);

// router
const route = useRoute();
const router = useRouter();

// tab选中
const tabsActiveKey = ref('1');

// 流程定义id
const definitionId = ref('');

// ref
const workFlowFormRef = ref();

const loading = ref(false);

// 是否显示保存草稿
const showSave = ref(true);
// 保存的名
const saveAliasName = ref('保存');

// 是否显示提交按钮
const showSubmit = ref(true);
// 提交的名
const submitAliasName = ref('提交');

// 是否显示抄送按钮
const showCopyTo = ref(true);
// 抄送的名
const copyToAliasName = ref('抄送');

// 是否显示流程预测
const showFlowPrediction = ref(false);

// 流程预测参数
const flowPredictionParams = ref({});

// 是否显示添加抄送人弹框
const showFlowCopy = ref(false);

// 抄送人列表
const copyToUserList = ref([]);

onMounted(() => {
  tabsActiveKey.value = '1';
  generatorStore.setFlowStartActiveTab('1');
  if (props.draft) {
    if (!props.definitionId) {
      back();
    } else {
      definitionId.value = props.definitionId;
    }
  } else {
    if (!route.query?.definitionId) {
      back();
    } else {
      definitionId.value = route.query.definitionId;
    }
  }
  getApplicantButtonPermission();
});

watch(
  () => flowStartActiveTab.value,
  val => {
    tabsActiveKey.value = val;
  },
  { deep: true }
);

// 获取指定流程定义下，可以操作的按钮权限
const getApplicantButtonPermission = () => {
  if (definitionId.value) {
    FlowStartApi.getApplicantButtonPermission({ definitionId: definitionId.value }).then(res => {
      showSave.value = res.save;
      if (res.saveAliasName) {
        saveAliasName.value = res.saveAliasName;
      }
      showSubmit.value = res.submit;
      if (res.submitAliasName) {
        submitAliasName.value = res.submitAliasName;
      }
      showCopyTo.value = res.copyTo;
      if (res.copyToAliasName) {
        copyToAliasName.value = res.copyToAliasName;
      }
    });
  }
};

// 返回
const back = () => {
  if (props.draft) {
    emits('closeDraft');
  } else {
    router.push('/mid/workflow/task/list');
  }
};
// 保存草稿
const save = async () => {
  const res = await workFlowFormRef.value.validateForm(false);
  if (res) {
    loading.value = true;
    let params = {
      definitionId: definitionId.value,
      instanceVariable: {},
      workflowStartType: 10
    };

    // 应用
    if (res.type == 'app') {
      params.instanceVariable.formData = res.formData;
    } else if (res.type == 'custom') {
      // 自定义
      params.instanceVariable.customVueFormData = res.formData;
    }

    // 是否是草稿
    if (props.draftId) {
      params.draftId = props.draftId;
    }
    FlowStartApi.saveDraft(params)
      .then(res => {
        message.success(res.message);
        back();
      })
      .finally(() => (loading.value = false));
  }
};

// 提交
const submit = async data => {
  if (!data) {
    const res = await workFlowFormRef.value.validateForm();
    if (res) {
      let params = {
        definitionId: definitionId.value,
        instanceVariable: {},
        workflowStartType: 10,
        copyToUserIdList: copyToUserList.value.map(item => item.id),
      };

      if (res.type == 'app') {
        params.instanceVariable.formData = res.formData;
      } else if (res.type == 'custom') {
        params.instanceVariable.customVueFormData = res.formData;
      }

      // 是否是草稿
      if (props.draftId) {
        params.draftId = props.draftId;
      }
      flowPredictionParams.value = params;
      console.log(params);
      showFlowPrediction.value = true;
    }
  } else {
    loading.value = true;
    FlowStartApi.start(data)
      .then(res => {
        message.success(res.message);
        back();
      })
      .finally(() => (loading.value = false));
  }
};

// 抄送
const copyTo = () => {
  showFlowCopy.value = true;
};

// 关闭添加抄送人
const closeAddCopyUser = data => {
  copyToUserList.value = data;
};
</script>

<style scoped lang="less">
.guns-layout-content {
  height: 100%;
  width: 100%;
  padding: 16px;
}
.content-mian-body {
  position: relative;
  overflow: hidden;
}
.start-btn {
  position: absolute;
  right: 0;
}
.blue-btn {
  color: var(--primary-color);
  font-weight: bold;
  border: 1px solid var(--primary-color);
}
:deep(.ant-tabs) {
  width: 100%;
  height: 100%;
}
:deep(.ant-tabs-content) {
  width: 100%;
  height: 100%;
}
:deep(.ant-tabs-content-holder) {
  overflow-y: auto;
  width: 100%;
  height: 100%;
}
.content-header {
  height: 41px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.back {
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  color: #60666b;
}
.back-icon {
  font-size: 14px;
  color: #b9bcbe;
}
</style>
