<template>
  <div>
    <a-divider orientation="left">{{ templateInfo.templateName }}表单</a-divider>
    <FormRender ref="formRenderRef" v-model="formData" :forms="forms" class="process-form" />
    <a-divider orientation="left">审批流程</a-divider>

    <div v-if="flowProcessNodes.length > 0" class="flow-preview-box">
      <div class="flow-preview-nodes">
        <a-timeline>
          <a-timeline-item
            v-for="(node, index) in flowProcessNodes"
            :key="index"
            :color="flowTimeLineDotColors[node.type].color"
          >
            <!-- 开始节点 -->
            <div v-if="node.type === NODE.START" class="node-box">
              <div class="node-name">开始</div>
            </div>

            <!-- 审批节点 -->
            <div v-else-if="node.type === NODE.APPROVE" class="node-box">
              <div class="node-name">
                审批
                <div class="node-type" v-if="node.examineMode === 3 || (node.nodeAssigneeList && node.nodeAssigneeList.length === 1)">
                  只需一人审批同意
                </div>
                <div class="node-type" v-else-if="node.examineMode === 1 || node.examineMode === 2">
                  需所有人审批同意
                </div>
                <div class="node-type" v-else-if="node.examineMode === 4">
                  需总权重大于50%
                </div>
              </div>
              <div class="node-content">
                <div v-if="node.selectMode === 1 || node.selectMode === 2" class="initator-chioce">
                  <a-button size="small" type="dashed" icon="plus" />
                </div>
                <div v-else class="node-assignee">
                  <FlowNodeAvatar
                    v-for="userId in node.userIds || []"
                    :key="userId"
                    :user-id="userId"
                    :set-type="node.setType || 1"
                    :size="24"
                    class="assignee-item"
                  />
                </div>
              </div>
            </div>

            <!-- 抄送节点 -->
            <div v-else-if="node.type === NODE.COPY" class="node-box">
              <div class="node-name">抄送</div>
              <div class="node-content">
                <div class="node-cc">
                  <template v-if="node.userIds && node.userIds.length">
                    <FlowNodeAvatar
                      v-for="userId in node.userIds"
                      :key="userId"
                      :user-id="userId"
                      :set-type="node.setType || 1"
                      :size="24"
                      class="assignee-item"
                    />
                  </template>
                  <template v-else>
                    <div class="null-tooltip">没有抄送人</div>
                  </template>
                </div>
              </div>
            </div>

            <!-- 结束节点 -->
            <div v-else-if="node.type === NODE.END" class="node-box">
              <div class="node-name">结束</div>
            </div>
          </a-timeline-item>
        </a-timeline>
      </div>
    </div>

    <a-alert v-else type="warning" show-icon message="必填信息填写完整后，将显示审批流程，之后方可提交审批。" />
  </div>
</template>

<script>
import FormRender from '@/views/workFlow/designer/common/form/FormRender.vue';
import FlowNodeAvatar from '@/views/workFlow/workspace/component/flowNodeAvatar.vue';
import { NODE } from '@views/workFlow/common/flowConstant'
import { getAction, postAction } from '@api/manage'

export default {
  name: 'FlowStart',
  components: {
    FormRender,
    FlowNodeAvatar
  },
  props: {
    templateId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      templateInfo: {
        templateId: '',
        templateName: '',
        logo: '',
        formItems: [],
        process: {},
        remark: '',
        settings: {}
      },
      formData: {},
      flowProcessNodes: [],
      flowTimeLineDotColors: {
        [NODE.START]: { color: '#a9b4cd' },
        [NODE.APPROVE]: { color: '#ff943e' },
        [NODE.COPY]: { color: '#3296fa' },
        [NODE.END]: { color: '#a9b4cd' }
      }
    };
  },
  computed: {
    NODE() {
      return NODE
    },
    forms() {
      return this.templateInfo.formItems;
    }
  },
  watch: {
    formData: {
      handler() {
        this.flowPreview(false);
      },
      deep: true
    }
  },
  mounted() {
    this.loadTemplateDetail();
  },
  methods: {
    loadTemplateDetail() {
      getAction('/workflow/template/detail',{templateId:this.templateId}).then(res => {
        const info = res.result;
        info.settings = JSON.parse(info.settings || '{}');
        info.formItems = JSON.parse(info.formItems || '[]');
        info.process = JSON.parse(info.process || '{}');
        this.templateInfo = info;
        // console.log("******templateInfo",JSON.stringify(info))
        this.$nextTick(() => {
          this.flowPreview(true);
        });
      });
    },
    flowPreview(clean) {
      const formRender = this.$refs.formRenderRef;
      if (!formRender || typeof formRender.validate !== 'function') {
        console.warn('FormRender validate 不存在，跳过 flowPreview');
        return;
      }
      formRender.validate(success => {
        if (clean && typeof formRender.reset === 'function') formRender.reset();
        // console.log("*******success",success)
        if (success) {
          const params = {
            templateId: this.templateId,
            variable: this.formData
          };
          postAction('/workflow/workspace/process/preview', params).then(res => {
            this.flowProcessNodes = res.result || [];
          });
        }
      });

    },
    validate(cb) {
      const formRender = this.$refs.formRenderRef;
      if (!formRender || typeof formRender.validate !== 'function') {
        cb && cb(false);
        return;
      }
      formRender.validate(success => cb && cb(success));
    }
  }
};
</script>

<style scoped lang="less">
.flow-preview-box {
  user-select: none;
  margin-top: 16px;

  .flow-preview-nodes {
    margin-top: 8px;

    .node-box {
      .node-name {
        display: flex;
        flex-direction: row;
        align-items: baseline;

        .node-type {
          font-size: 12px;
          color: #8f959e;
          margin-left: 4px;
        }
      }

      .node-content {
        margin-bottom: 30px;

        .node-assignee,
        .node-cc {
          margin-top: 4px;
          display: flex;
          flex-flow: row wrap;
          gap: 6px;
        }

        .assignee-item {
          margin-right: 4px;
          margin-top: 4px;
          max-width: 120px;
        }

        .null-tooltip {
          font-weight: 400;
          color: #86909c;
          font-size: 12px;
        }

        .initator-chioce {
          margin-top: 4px;
          display: flex;

          .assignee-list {
            flex: 1;
            margin-left: 10px;
            display: grid;
            gap: 4px;
            grid-template-columns: repeat(auto-fill, minmax(70px, max-content));
          }
        }
      }
    }
  }
}
</style>
