<template>
  <div class="processApproval">
    <div class="left-card">
      <div class="top">
        <div class="commons-title title">
          {{
            route.query.flowName
              ? route.query.flowName + (route.query.processType ? typeName[route.query.processType] : "（发起）")
              : keyName[route.query.flowKey] + "（审批）"
          }}
        </div>
        <div class="line"></div>
        <Subscribe :queryData="detailsData.data" v-if="route.query.flowKey == 'apply_buy'" ref="makeDom"></Subscribe>
        <Purchase :queryData="detailsData.data" v-else-if="route.query.flowKey == 'purchase'" ref="makeDom"></Purchase>
      </div>
      <div class="bottom" v-if="route.query.processType != 20">
        <div class="commons-title title">处理意见</div>
        <el-form :model="flowForm" :rules="flowRules" ref="flowFormDom">
          <el-form-item prop="remark" label-width="0px" label="">
            <el-input type="textarea" placeholder="请输入" v-model="flowForm.remark"> </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" v-if="!route.query.processType || ['30', '40'].includes(route.query.processType)" @click="handleSaveDraft" v-preReClick>
              保存草稿
            </el-button>
            <el-button type="primary" v-if="approvalRecordData.buttonInfoList.length == 0" @click="handleSubmit" v-preReClick>提交</el-button>
            <el-button type="primary" v-else v-for="i in approvalRecordData.buttonInfoList" :key="i.type" @click="handleSubmit(i.type)" v-preReClick>
              {{ i.name }}
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="right-card">
      <el-tabs v-model="activeName" class="demo-tabs">
        <el-tab-pane label="审批记录" name="first">
          <ul class="flow-chart">
            <li
              v-for="item in recordList"
              :key="item.id"
              :class="
                !route.query.flowId
                  ? ''
                  : item.status == 2
                  ? 'flow-orange'
                  : item.status == 3 && !route.query.flowId
                  ? 'flow-orange'
                  : item.status == 3 && route.query.flowId
                  ? 'flow-grey'
                  : ''
              ">
              <div class="left-icon">
                <i class="iconfont icon-iconm_daick"></i>
                <i class="iconfont icon-icomx_quertj1 right-btm-status"></i>
              </div>
              <div class="right-conetnt">
                <div class="name">{{ item.nodeName }}</div>
                <div class="remark">
                  <div class="label">
                    <span v-if="item.status != 3">办理人：</span>{{ item.processedUser }}<span class="time">{{ item.processedDate }}</span>
                  </div>
                  {{ item.remark }}
                  <div v-for="j in fileObj[item.flowExampleDetailId]" v-if="fileObj[item.flowExampleDetailId]">
                    <a :href="j.fileUrl" style="color: #409eff; line-height: 30px">{{ j.fileName }}</a>
                  </div>
                </div>
              </div>
              <div class="line"></div>
            </li>
          </ul>
        </el-tab-pane>
      </el-tabs>
    </div>

    <el-dialog title="下一处理人" width="400" v-model="dialogVisible">
      <el-form :model="flowForm">
        <el-form-item prop="remark" label="处理人">
          <el-select v-model="flowForm.handleUserId" placeholder="请选择" filterable style="width: 100%">
            <el-option v-for="item in nextHandleUser" :label="item.name" :value="item.id"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <div style="width: 100%; text-align: center">
            <el-button type="primary" @click="handleSelectUser">提交</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import useTagsViewStore from "@/store/modules/tagsView.js";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
// 申购单
import Subscribe from "@/components/process/subscribe";
// 采购合同
import Purchase from "@/components/process/purchase";

const typeName = ref({
  10: "（审批）",
  20: "（详情）",
  30: "（发起）",
  40: "（发起）",
});
const keyName = ref({
  apply_buy: "申购流程",
  purchase: "采购流程",
});
const flowKeyCollect = reactive({
  apply_buy: {
    backPath: "/group/oa/subscribe",
    edit: "/applyBuy/edit",
    add: "/applyBuy/add",
    detail: "/applyBuy/detail",
  },
  purchase: {
    backPath: "/group/purchase/purchase-contract",
    edit: "/purchase/edit",
    add: "/purchase/add",
    detail: "/purchase/detail",
  },
});
const detailsData = reactive({
  data: {},
});
const router = useRouter();
const route = useRoute();
// tab切换逻辑
const activeName = ref("first");
// 意见表单
const flowForm = reactive({
  flowKey: "",
  tenantType: "",
  handleUserId: "",
  remark: "",
  data: {},
  fileList: [],
});
const flowRules = reactive({
  // remark: [{ required: true, message: "请输入处理意见", trigger: "blur" }],
});

//组件实例
const { proxy } = getCurrentInstance();
const flowFormDom = ref(null);
let dialogVisible = ref(false);
const nextHandleUser = ref([]);
const handleSelectUser = () => {
  if (!flowForm.handleUserId) {
    return ElMessage({
      message: "请选择下一节点处理人！",
      type: "info",
    });
  }
  handleSubmit();
};
const handleResult = (res) => {
  if (res !== null && res.success) {
    skipPage();
  } else {
    dialogVisible.value = true;
    nextHandleUser.value = res.userList;
  }
};
// 提交逻辑
const handleSubmit = async (_type) => {
  try {
    // 调用发起组件的提交事件
    const flag = await proxy.$refs.makeDom.handleSubmit();
    if (flag) {
      flowFormDom.value.validate((valid) => {
        if (valid) {
          const data = { ...proxy.$refs.makeDom.getFormData() };
          if (route.query.processType == "10" || route.query.processType == "30") {
            if (_type && _type == 1) {
              proxy
                .post("/flowExample/setStartData", {
                  exampleId: route.query.flowId,
                  startData: data,
                })
                .then();
            }
            proxy
              .post("/flowProcess/jump", {
                ...flowForm,
                data,
                handleType: _type,
                version: route.query.version,
                flowId: route.query.flowId,
              })
              .then((res) => {
                handleResult(res);
              });
            return;
          } else {
            proxy
              .post("/flowProcess/initiate", {
                ...flowForm,
                data,
              })
              .then((res) => {
                handleResult(res);
              });
          }
        }
      });
    }
  } catch (err) {
    console.log("数据未填完整！", err);
  }
};
// 页面跳转
const skipPage = () => {
  const useTagsStore = useTagsViewStore();
  useTagsStore.delVisitedView(router.currentRoute.value);
  if (route.query.processType && route.query.processType != "40") {
    router.replace({
      path: "/oa/1/dealWith",
    });
  } else {
    ElMessage({ message: "操作成功!", type: "success" });
    router.replace({
      path: flowKeyCollect[route.query.flowKey].backPath,
    });
  }
};
let queryData = reactive({
  data: {},
});
// 记录
const recordList = ref([]);
const fileIds = ref([]);
const fileObj = ref({});
const approvalRecordData = ref({
  buttonInfoList: [],
});
const getRecords = (_id) => {
  if (_id) {
    proxy
      .post("/flowExample/getApprovalRecord", {
        id: _id,
      })
      .then((res) => {
        recordList.value = res.recordList;
        queryData.data.recordList = res.recordList;
        approvalRecordData.value = res;
        fileIds.value = res.recordList.map((item) => {
          return item.flowExampleDetailId;
        });
        proxy.post("fileInfo/getList", { businessIdList: fileIds.value }).then((res2) => {
          fileObj.value = res2;
        });
      });
  } else {
    proxy
      .post("/flowExample/getFlowNode", {
        flowKey: route.query.flowKey,
      })
      .then((res) => {
        recordList.value = res;
      });
  }
};
const handleSaveDraft = async () => {
  const flag = await proxy.$refs.makeDom.handleSubmit();
  if (flag) {
    let data = proxy.$refs.makeDom.getFormData();
    if (data.id) {
      proxy.post(flowKeyCollect[route.query.flowKey].edit, data).then(() => {
        skipPage();
      });
    } else {
      proxy.post(flowKeyCollect[route.query.flowKey].add, data).then(() => {
        skipPage();
      });
    }
  }
};
onMounted(() => {
  //processType 10 为修改 20为查看 30回退发起
  flowForm.flowKey = route.query.flowKey;
  flowForm.tenantType = route.query.tenantType;
  if (route.query.random) {
    useTagsViewStore().visitedViews = useTagsViewStore().visitedViews.map((item) => {
      if (item.query && item.query.random === route.query.random) {
        return {
          ...item,
          name: route.query.flowName,
          title: route.query.flowName,
        };
      } else {
        return {
          ...item,
        };
      }
    });
  }
  if (route.query.id) {
    proxy.post(flowKeyCollect[route.query.flowKey].detail, { id: route.query.id }).then((res) => {
      detailsData.data = { ...res };
    });
  }
  getRecords(route.query.flowId);
});
</script>
<style>
.el-upload-list {
  float: left;
  margin: 0 !important;
}
.el-upload-list li {
  width: 100px;
  margin-left: 10px;
}
.el-upload--text {
  float: left;
}
</style>
<style lang="scss" scoped>
.processApproval {
  display: flex;
  justify-content: space-between;
  height: calc(100vh - 120px);
  .left-card {
    border-radius: 4px;
    width: calc(100% - 400px - 10px);
    margin-right: 10px;
    display: flex;
    flex-direction: column;
    .top {
      flex: 1;
      overflow-y: auto;
      overflow-x: hidden;
      background: #fff;
      padding: 20px;
      .line {
        border-bottom: 1px solid #ddd;
        margin-bottom: 10px;
      }
    }
    .bottom {
      margin-top: 10px;
      height: 190px;
      background: #fff;
      padding: 20px;
      overflow-y: auto;
      overflow-x: hidden;
    }
  }
  .right-card {
    background: #fff;
    border-radius: 4px;
    padding: 0 20px 20px;
    width: 400px;
    box-sizing: border-box;
    .flow-chart {
      overflow-y: auto;
      overflow-x: hidden;
      height: calc(100vh - 200px);
      padding: 0;
      margin: 0;
      li {
        margin: 0;
        padding: 0 0 20px;
        list-style: none;
        display: flex;
        justify-content: space-between;
        position: relative;
        .right-conetnt {
          flex: 1;
          .name {
            font-size: 12px;
            color: #39c55a;
            margin-bottom: 10px;
            span {
              color: #999;
            }
          }
          .time {
            float: right;
          }
          .remark {
            padding: 10px;
            color: #666666;
            font-size: 12px;
            background: #f1f1f1;
            border-radius: 2px;
            .label {
              color: #999;
              margin-bottom: 10px;
            }
          }
        }
        .left-icon {
          width: 40px;
          height: 40px;
          text-align: center;
          line-height: 40px;
          background: #0084ff;
          border-radius: 10px;
          color: #fff;
          font-size: 20px;
          position: relative;
          margin-right: 27px;
          z-index: 2;
          .right-btm-status {
            position: absolute;
            bottom: 0px;
            right: -10px;
            height: 20px;
            width: 20px;
            line-height: 16px;
            border-radius: 10px;
            background: #39c55a;
            border: 2px solid #fff;
            font-size: 12px;
            box-sizing: border-box;
          }
        }
      }
      li::before {
        content: "";
        position: absolute;
        top: 0;
        left: 20px;
        width: 2px;
        height: 100%;
        background: #ddd;
        z-index: 1;
      }
      li:last-child::before {
        display: none;
      }
      .flow-orange {
        .right-btm-status {
          background: #ff9a00 !important;
        }
        .name {
          color: #ff9a00 !important;
        }
        .left-icon {
          background: #ff9a00 !important;
        }
      }
      .flow-grey {
        .right-btm-status {
          background: #999 !important;
        }
        .name {
          color: #999 !important;
        }
        .left-icon {
          background: #999 !important;
        }
      }
      .flow-red {
        .right-btm-status {
          background: #ff4d4f !important;
        }
        .name {
          color: #ff4d4f !important;
        }
        .left-icon {
          background: #ff4d4f !important;
        }
      }
    }
  }
}
</style>
