<template>
  <BasicModal
    width="1200px"
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    :useWrapper="true"
    :minHeight="500"
  >
    <div class="process-cofig">
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 2 }"
        :wrapper-col="{ span: 4 }"
        style="height: 100%"
      >
        <div class="info-item info-item-basic">
          <div class="title">基本信息</div>
          <div class="form-continer">
            <a-form-item label="业务类型" name="type">
              <a-select
                v-model:value="formState.type"
                placeholder="请选择业务类型"
                :disabled="optType !== 1"
                @change="businessChange"
              >
                <template v-for="item in dicBusiness" :key="item.value">
                  <a-select-option :value="item.value">{{ item.label }}</a-select-option>
                </template>
              </a-select>
            </a-form-item>
          </div>
        </div>
        <div class="info-item info-item-steps">
          <div class="title">步骤配置</div>
          <div class="form-continer">
            <div class="left-continer">
              <a-table
                v-if="formState.steps.length > 0"
                bordered
                rowKey="xh"
                :data-source="formState.steps"
                :columns="pColumns"
                :pagination="false"
                :customRow="customRow"
                style="height: 100%"
              >
                <template #operation="{ record }">
                  <a style="color: #2d74e7" @click="editStep(record)" v-if="record.xh !== 1"
                    ><span v-if="optType !== 3">编辑</span><span v-else>查看</span></a
                  >
                  <a style="color: #9b9c9e" v-else>编辑</a
                  >
                </template>
              </a-table>
            </div>
            <div class="right-continer">
              <add-step-form
                :currStep="currStep"
                :optType="optType"
                @editStep="updateStep"
                @reduceStep="reduceStep"
                ref="addStepForm"
              ></add-step-form>
            </div>
          </div>
        </div>
      </a-form>
    </div>
  </BasicModal>
</template>
<script lang="ts">
import { ValidateErrorEntity } from 'ant-design-vue/es/form/interface';
import {
  defineComponent,
  ref,
  computed,
  unref,
  reactive,
  onMounted,
  UnwrapRef,
  toRaw,
  nextTick,
} from 'vue';
import { BasicModal, useModalInner } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { accountFormSchema, accountFormSchema2, busType, stepColumns } from './configData';
import { useMessage } from '/@/hooks/web/useMessage';
import AddStepForm from './addStepForm.vue';
import { getBuildUUID } from '/@/utils/uuid';
import { addFlowInfoAll } from '/@/api/resource/examine';
interface StepInfo {
  xh: number;
  name: string;
  model: string;
  dept: string[];
  user: string[];
}
interface FormState {
  type: string;
  name: string;
  steps: StepInfo[];
}
interface FlowNode {
  flowid: string; //流程id
  id: string; //流程步骤id
  nodename: string; //结点名称
  prenodeid: string; //上一个结点id
  nextnodeid: string; //下一个结点id
  nodediscription: string; //结点描述
  model: string; //审核模式
  depts: string; //审核部门
}

interface FlowNodePerson {
  flownodeid: string; //流程结点id
  id: string; //审核id
  userid: string; //审核人id
  preuserid: string; //上一个审核人id
  nextuserid: string; //下一个审核人id
  nodetype: string; //结点类型
}
export default defineComponent({
  name: 'AccountModal',
  components: {
    BasicModal,
    BasicForm,
    AddStepForm,
  },
  emits: ['success', 'register'],
  setup(_, { emit }) {
    const formRef = ref();
    let show1 = ref(true);
    const isUpdate = ref(true);
    const optType = ref(1); //操作类型  1：新增，2：修改 3:查看
    const rowId = ref('');
    const currVersion = ref(0); //当前版本
    const postData = ref(null);
    const formState = reactive({
      type: '',
      name: '',
      steps: ref([{ xh: 1, name: '', model: 'update', dept: [], user: [], userList: [] }]),
    });

    const rules = {
      type: [{ required: true, message: '请选择业务类型', trigger: 'change' }],
      steps: [{ required: true, message: '请配置审核步骤', trigger: 'change', type: 'array' }],
    };
    const dicBusiness = busType;
    const pColumns = stepColumns;
    const currStep = ref();
    const addStepForm = ref(null);
    const { createMessage } = useMessage();

    onMounted(() => {});
    const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
      labelWidth: 100,
      schemas: show1 ? accountFormSchema : accountFormSchema2,
      showActionButtonGroup: false,
      actionColOptions: {
        span: 18,
      },
    });

    const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
      await resetFields();
      setModalProps({ confirmLoading: false });
      isUpdate.value = !!data?.isUpdate;
      postData.value = data?.record ? data.record : null;
      //修改
      if (isUpdate.value) {
        optType.value = 2; //操作类型  1：新增，2：修改 3:查看
        rowId.value = data.record.id;
        //setFieldsValue(data.record);
        setFormdata();
      } else {
        if (postData.value) {
          //查看
          optType.value = 3;
          //setFieldsValue(data.record);
          setFormdata();
        } else {
          //新增
          optType.value = 1;
          //初始化
          clearFormData();
        }
      }
    });

    const getTitle = computed(() =>
      !unref(isUpdate) ? (unref(postData) ? '查看流程配置' : '新增流程配置') : '编辑流程配置'
    );

    /**
     * 根据查询的接口数据设置表单数据
     */
    const setFormdata = async () => {
      if (postData.value) {
        const flowInfo = (postData.value as any).flowInfo;
        const flowNode = (postData.value as any).flowNode;
        const flowNodePerson = (postData.value as any).flowNodePerson;
        currVersion.value = parseInt(flowInfo?.VERSION ? flowInfo?.VERSION : 0); //获取当前本版
        const dbs = dicBusiness.find((item) => item.label === flowInfo['FLOWNAME']);
        formState.type = dbs ? dbs.value : '0';
        formState.name = flowInfo['FLOWNAME'];
        formState.steps = [
          { xh: 1, name: flowInfo['FLOWNAME'], model: '1', dept: [], user: [], userList: [] },
        ];

        flowNode.map((item, index) => {
          const user = flowNodePerson.filter((fp) => item['ID'] === fp['FLOWNODEID']);
          let model = '2' //并行
          //判断是串行还是并行，如果存在生一个审核人或者下一个审核人则为逐级，否则就是并行
          user.map(item =>{
            if(item['NEXTUSERID'] !== '' || item['PREUSERID'] != '') model = '1'
          })
          
          formState.steps.push({
            xh: index + 2,
            name: item['NODENAME'],
            model: user[0]['NODETYPE'] || model,
            dept: item['DEPTS'].split(','),
            user: user
              ? user.map((u) => {
                  return u['USERID'];
                })
              : [],
            userList: [],
          });
        });

        currStep.value = formState.steps[0];
      }
    };

    /**
     * 提交数据
     */
    async function handleSubmit() {
      setModalProps({ confirmLoading: true });
      try {
        //校验当前界面是否数据完整
        const flag = await (addStepForm.value as any).validateForm();
        if (!flag) {
          return createMessage.warning('请填写必填数据');
        }
        formRef.value
          .validate()
          .then(() => {
            const forms = toRaw(formState) as any;
            if (forms.steps.value.length < 2) {
              createMessage.warning('请维护至少两个步骤');
              return;
            }
            addProcess(forms);
          })
          .catch((error: ValidateErrorEntity<FormState>) => {
            console.log('error', error);
          });
      } finally {
        setTimeout(() => {
          setModalProps({ confirmLoading: false });
        }, 300);
      }
    }

    function preProcessData(data) {
      Object.keys(data).forEach((item) => {
        if (typeof data[item] === 'undefined' || data[item] === null || data[item] === '') {
          delete data[item];
        }
      });
      return data;
    }

    function paramsToFormData(obj) {
      const data = preProcessData(obj);
      const formData = new FormData();
      Object.keys(data).forEach((key) => {
        if (data[key] instanceof Array) {
          data[key].forEach((item) => {
            formData.append(key, item);
          });
          return;
        }
        formData.append(key, obj[key]);
      });
      return formData;
    }

    /**
     * 编辑步骤
     */
    const editStep = (row) => {
      currStep.value = row;
    };

    /**
     * 修改步骤
     */
    const updateStep = (row) => {
      nextTick(() => {
        const obj = formState.steps.find((item) => item.xh === row.xh);
        if (obj) {
          formState.steps.forEach((item) => {
            if (item.xh === row.xh) {
              for (const key in row) {
                item[key] = row[key];
              }
            }
          });
        } else {
          formState.steps.push(row);
        }
      });
    };

    const reduceStep = (row) => {
      const obj = formState.steps.find((item) => item.xh === row.xh);
      const index = formState.steps.indexOf(obj as any);
      if (index > -1) formState.steps.splice(index, 1);
      //当前数据显示最后一个
      currStep.value = formState.steps[formState.steps.length - 1];
    };

    const businessChange = (value) => {
      const obj = dicBusiness.find((item) => item.value === value);
      if (obj) formState.steps[0].name = obj.label;
      currStep.value = formState.steps[0];
      if (obj) formState.name = obj.label;
    };

    /**
     * 新增流程
     */
    const addProcess = async (fdata) => {
      const processInfo = formDataHandle(fdata) as any;
      //console.log('提交数据', processInfo);
      const res = (await addFlowInfoAll(processInfo)) as any;
      if (res && res.resp_code === 0) {
        closeModal();
        emit('success');
        createMessage.success(unref(isUpdate) ? '编辑成功' : '新增成功');
        //清理数据
        clearFormData();
      } else {
        createMessage.error('数据提交失败!失败原因：' + res.resp_msg);
      }
    };
    /**
     * 清空数据
     */
    const clearFormData = () => {
      resetForm();
      formState.type = '';
      formState.name = '';
      formState.steps = [{ xh: 1, name: '', model: 'update', dept: [], user: [], userList: [] }];
      currStep.value = null;
      (addStepForm.value as any)?.clearFormData();
    };

    /**
     * 生成提交的数据
     */
    const formDataHandle = (formData) => {
      //const uuid = buildUUID()
      const flowId = getBuildUUID(); //生成流程id
      //流程数据
      let flowInfo = {
        flowdiscription: '',
        flowname: formData.name,
        id: flowId,
        version: optType.value === 1 ? 0 : currVersion.value + 1,
      };
      //排除第一个
      const steps = formData.steps.value.filter((step) => step.xh !== 1);
      //生成步骤结点id
      steps.forEach((item) => {
        item['id'] = getBuildUUID();
      });

      //流程结点数据
      let flowNode: Array<FlowNode> = [];
      //审核人数据
      let flowNodePerson: Array<FlowNodePerson> = [];
      //生成流程结点数据
      for (let i = 0; i < steps.length; i++) {
        flowNode.push({
          flowid: flowId,
          id: steps[i].id,
          nodename: steps[i].name, //结点名称
          prenodeid: i === 0 ? '' : steps[i - 1].id, //上一个结点id
          nextnodeid: i < steps.length - 1 ? steps[i + 1].id : '', //下一个结点id
          nodediscription: steps[i].name, //结点描述
          model: steps[i].model,
          depts: steps[i].dept.toString(),
        });
      }
      //生成审核人id
      steps.forEach((item) => {
        item.userList.forEach((user) => {
          user['id'] = getBuildUUID();
        });
      });

      //生成审核数据
      for (let i = 0; i < steps.length; i++) {
        const step = steps[i];
        for (let j = 0; j < step.userList.length; j++) {
          let preuserid = ''; //上一个审核人id
          let nextuserid = ''; //下一个审核人id
          //model 1:逐级   2:并行
          //逐级审核获取前一个审核人和后一个审核人
          if (step.model === '1') {
            //步骤结点的第一个审核人
            if (j === 0) {
              ////第一个审核步骤，第一个审核人
              // if (i === 0){
              //   preuserid = '';   //此时第一个审核人没有上一个审核人
              // }
              // else {
              //   //不是第一个审核步骤，不是第一个审核人,则选择上一个结点的最后一个审核人
              //   const userList = steps[i - 1].userList;
              //   preuserid = userList[userList.length - 1].userId;
              // }
              preuserid = '';
            } else {
              //步骤结点的非第一个审核人
              preuserid = step.userList[j - 1].userId;
            }
            //步骤结点的最后一个审核人
            if (j === step.userList.length - 1) {
              //也是最后一个步骤结点
              // if(i === (steps.length - 1)){
              //   nextuserid = ''  //下一个审核人不存在
              // }
              // else{   //不是最后一个步骤结点
              //   nextuserid = steps[i + 1].userList[0].userId  //下一个审核步骤结点的第一个审核人
              // }
              nextuserid = ''; //下一个审核人不存在
            }
            //不是步骤的最后一个审核人
            else {
              nextuserid = steps[i].userList[j + 1].userId; //下一个审核步骤结点的第一个审核人
            }
          }
          //model 1:逐级   2:并行
          //并行审核获取前一个审核人和后一个审核人
          if (step.model === '2') {
            preuserid = '';
            nextuserid = '';
          }

          const user = step.userList[j];
          flowNodePerson.push({
            flownodeid: step.id, //流程结点id
            id: user.id, //审核id
            userid: user.userId, //审核人id
            preuserid: preuserid, //上一个审核人id
            nextuserid: nextuserid, //下一个审核人id
            nodetype: step.model, //结点类型
          });
        }
      }
      return { flowInfo, flowNode, flowNodePerson };
    };

    const resetForm = () => {
      formRef.value.resetFields();
    };

    const customRow = (record, index) => {
      console.log(record, index);
      return {
        on: {
          // 鼠标单击行
          click: (event) => {
            event.currentTarget.parentNode.querySelectorAll('tr').forEach((item) => {
              item.style.background = 'white';
            });
            event.currentTarget.style.background = 'green';
          },
        },
      };
    };

    return {
      optType,
      currVersion,
      postData,
      formRef,
      formState,
      rules,
      dicBusiness,
      pColumns,
      currStep,
      addStepForm,
      createMessage,
      customRow,
      registerModal,
      registerForm,
      handleSubmit,
      getTitle,
      show1,
      resetForm,
      editStep,
      updateStep,
      reduceStep,
      businessChange,
      addProcess,
      formDataHandle,
      setFormdata,
      clearFormData,
      paramsToFormData,
    };
  },
});
</script>
<style scoped lang="less">
.process-cofig {
  position: absolute;
  height: calc(100% - 14px);
  width: calc(100% - 30px);
  padding: 0 20px;

  .info-item {
    width: 100%;
    margin-bottom: 20px;
    .title {
      padding-left: 10px;
      border-left: 3px solid #2d74e7;
      height: 16px;
      line-height: 16px;
      font-family: Source Han Sans CN;
      font-size: 16px;
      font-weight: 300;
      letter-spacing: 0px;
      color: #333333;
    }
    .form-continer {
      padding-top: 20px;
      height: calc(100% - 36px);
      .left-continer {
        float: left;
        height: 100%;
        width: 440px;
        padding: 20px;
        background: #ffffff;
        box-shadow: 0px 0px 2px 0px rgba(0, 0, 0, 0.1), inset 0px 2px 2px 0px rgba(0, 0, 0, 0.05);
      }
      .right-continer {
        float: right;
        padding: 20px;
        height: 100%;
        width: calc(100% - 440px);
        background: #ffffff;
        box-shadow: 0px 0px 2px 0px rgba(0, 0, 0, 0.1), inset 0px 2px 2px 0px rgba(0, 0, 0, 0.05);
      }
    }
  }
  .info-item-basic {
    height: 68px;
  }
  .info-item-steps {
    height: calc(100% - 88px);
  }
}
</style>
