<template>
  <view class="content">
    <view class="title"> 项目详情 </view>
    <view class="main">
      <view class="list">
        <view class="detail">
          <span class="subTitle">项目名称:</span>
          <span class="detailContent">{{ currentProject.project_name }}</span>
        </view>
        <view class="detail" v-if="currentProject.TypeInfo">
          <span class="subTitle">项目类别:</span>
          <span class="detailContent">{{ currentProject.TypeInfo.name }}</span>
        </view>
        <view class="detail" v-if="currentProject.IndustryInfo">
          <span class="subTitle">行业名称:</span>
          <span class="detailContent">
            {{ currentProject.IndustryInfo.name }}
          </span>
        </view>
        <view class="detail">
          <span class="subTitle">流程:</span>
          <span class="detailContent">{{ currentProject.FlowInfo.name }}</span>
        </view>
        <view class="detail">
          <span class="subTitle">状态:</span>
          <span class="detailContent">
            {{ status[currentProject.project_status] }}
          </span>
        </view>
        <view class="detail">
          <span class="subTitle">节点:</span>
          <span class="detailContent">
            {{ `${currentProject.NodeInfo.node}(` }}
            <span v-if="currentProject.audit_status == 0">待提交</span>
            <span
              v-if="currentProject.audit_status == 1"
              :style="{ color: '#1890ff' }"
            >
              审核中
            </span>
            <span
              v-if="currentProject.audit_status == 2"
              :style="{ color: '#f5222d' }"
            >
              审核拒绝
            </span>
            <span
              v-if="currentProject.audit_status == 3"
              :style="{ color: '#a0d911' }"
            >
              审核通过
            </span>
            <span>)</span>
          </span>
        </view>
        <view class="detail" v-if="currentProject.audit_status == 2">
          <span class="subTitle">拒绝原因:</span>
          <span class="detailContent">
            {{ currentProject.audit_comment }}
          </span>
        </view>
        <view class="detail" v-if="currentProject.location">
          <span class="subTitle">项目地区:</span>
          <span class="detailContent">
            {{ `${currentProject.location}(${currentProject.location_code})` }}
          </span>
        </view>
        <view class="detail" v-if="currentProject.name">
          <span class="subTitle">项目简称:</span>
          <span class="detailContent">{{ currentProject.name }}</span>
        </view>
        <view class="detail" v-if="currentProject.version">
          <span class="subTitle">项目批次:</span>
          <span class="detailContent">{{ currentProject.version }}期</span>
        </view>
        <view class="detail" v-if="currentProject.AuthorUser">
          <span class="subTitle">创建人:</span>
          <span class="detailContent">{{
            currentProject.AuthorUser.CName
          }}</span>
        </view>
        <view class="detail" v-if="currentProject.AuthorDepInfo">
          <span class="subTitle">所属部门:</span>
          <span class="detailContent">
            {{ currentProject.AuthorDepInfo.Name }}
          </span>
        </view>
        <view class="detail">
          <span class="subTitle">项目编号:</span>
          <span class="detailContent">
            {{ currentProject.project_full_code }}
          </span>
        </view>
      </view>

      <view class="title">审核详情 </view>
      <view class="list">
        <uni-steps
          :options="nodeList.list"
          :active="nodeList.currentIndex"
          direction="column"
        />
      </view>

      <uni-card title="操作" v-if="!this.auth">
        <view class="editBtns" slot="actions">
          <view class="edit" v-if="canEdit(0)" @click="onEdit()">编辑</view>
          <view class="edit" v-if="canEdit(0)" @click="onDelete()">删除</view>
          <view class="edit" v-if="canEdit(0)" @click="onSubmitAuth()">
            提交审核
          </view>
          <view class="edit" v-if="canEdit(1)" @click="onMember()"
            >成员管理
          </view>
          <view class="edit" v-if="canEdit(2)" @click="onExecute()">
            转执行
          </view>
          <view class="edit" v-if="canEdit(3)" @click="onWarranty()">
            转质保
          </view>
          <view class="edit" v-if="canEdit(3)" @click="onOperate()">
            转运营
          </view>
        </view>
      </uni-card>
    </view>

    <view class="group" v-if="this.auth && canAuth()">
      <button @click="onHandleAudit(0)" class="commit">审核拒绝</button>
      <button @click="onHandleAudit(1)" type="primary" class="commit">
        审核通过
      </button>
    </view>

    <uni-popup ref="exePopup" type="dialog">
      <uni-popup-dialog
        title="转执行"
        type="info"
        @confirm="submitExecute"
        @close="onCancel"
        before-close
      >
        <uni-forms
          ref="exe"
          :modelValue="formData"
          label-position="left"
          :rules="exeRules"
        >
          <uni-forms-item required label="执行经理:" name="manager">
            <uni-data-picker
              class="depSelect"
              placeholder="请选择执行经理"
              :localdata="depUserTree"
              @change="changeManager"
            />
          </uni-forms-item>
          <uni-forms-item required label="合同状态:" name="contract">
            <picker
              @change="changeContract"
              :range="contracts"
              :value="formData.contract"
            >
              <view class="select">{{ contracts[formData.contract] }}</view>
            </picker>
          </uni-forms-item>
        </uni-forms>
      </uni-popup-dialog>
    </uni-popup>
    <uni-popup ref="wtyPopup" type="dialog">
      <uni-popup-dialog
        title="转质保"
        type="info"
        @confirm="submitWarranty"
        @close="onCancel"
        before-close
      >
        <uni-forms
          ref="wty"
          :modelValue="formData"
          label-position="left"
          :rules="wtyRules"
        >
          <uni-forms-item required label="质保经理:" name="manager">
            <uni-data-picker
              class="depSelect"
              placeholder="请选择质保经理"
              :localdata="depUserTree"
              @change="changeManager"
            />
          </uni-forms-item>
        </uni-forms>
      </uni-popup-dialog>
    </uni-popup>
    <uni-popup ref="optPopup" type="dialog">
      <uni-popup-dialog
        title="转运营"
        type="info"
        @confirm="submitOperate"
        @close="onCancel"
        before-close
      >
        <uni-forms
          ref="opt"
          :modelValue="formData"
          label-position="left"
          :rules="optRules"
        >
          <uni-forms-item required label="运营经理:" name="manager">
            <uni-data-picker
              class="depSelect"
              placeholder="请选择运营经理"
              :localdata="depUserTree"
              @change="changeManager"
            />
          </uni-forms-item>
        </uni-forms>
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
import { mapState } from "vuex";
import {
  queryFlow,
  deleteApproval,
  submitAudit,
  queryUserDetail,
  authApproval,
  startExecution,
  startWarranty,
  startOperate,
} from "@/services/project";
import uniFormsItem from "../../uni_modules/uni-forms/components/uni-forms-item/uni-forms-item.vue";
const contracts = ["无合同", "有合同"];
export default {
  components: { uniFormsItem },
  data() {
    return {
      auth: false,
      status: ["售前", "转执行", "转运营", "转质保"],
      flowList: [],
      depRole: [],
      user: {},
      manager: "",
      contracts,
      formData: {
        manager: "",
        contract: null,
      },
      exeRules: {
        manager: {
          rules: [{ required: true, errorMessage: "请选择质保经理" }],
        },
        contract: {
          rules: [{ required: true, errorMessage: "请选择合同状态" }],
        },
      },
      wtyRules: {
        manager: {
          rules: [{ required: true, errorMessage: "请选择质保经理" }],
        },
      },
      optRules: {
        manager: {
          rules: [{ required: true, errorMessage: "请选择运营经理" }],
        },
      },
    };
  },
  computed: {
    ...mapState(["currentProject", "depUserTree"]),
    nodeList() {
      if (!this.flowList) return [];
      let flowInfo = this.flowList.find(
        (item) => item.id == this.currentProject.flow_id
      );
      if (!flowInfo) return [];
      let currentIndex = flowInfo.Nodes.findIndex(
        (item) => item.id == this.currentProject.node_id
      );
      return {
        currentIndex,
        list: flowInfo.Nodes.map((item) => ({
          title: item.node,
          desc: `审批人：${this.getAudits(item)}`,
        })),
      };
    },
  },
  onLoad(options) {
    this.auth = Boolean(options.auth);
    this.init();
  },
  methods: {
    async init() {
      this.user = uni.getStorageSync("user");
      let res;
      res = await queryFlow();
      this.flowList = res.data;
      res = await queryUserDetail(this.user);
      let depId = this.user.DepId;
      let dep = res.data.Dep.find((item) => item.ID == depId);
      this.depRole = dep.Role;
    },

    canAuth() {
      let { NodeInfo, audit_status, project_status } = this.currentProject;
      if (!NodeInfo || this.flowList.length == 0 || this.depRole.length == 0)
        return false;
      if (audit_status != 1) return false;

      if (project_status == 2)
        return this.currentProject.opt_manager_id == this.user.ID;
      if (project_status == 3)
        return this.currentProject.wty_manager_id == this.user.ID;

      let flow = this.flowList.find((item) => item.id == NodeInfo.flow_id);
      if (!flow) return false;
      let { NodeAudits } = flow.Nodes.find((item) => item.id == NodeInfo.id);
      const role = this.depRole.find((item) =>
        NodeAudits.find((audit) => audit.audit_role == item.ID)
      );
      return Boolean(role);
    },
    onHandleAudit(value) {
      if (value) {
        uni.showModal({
          title: "审批通过",
          content: "是否确认通过审批",
          confirmText: "通过",
          success: async (res) => {
            if (res.confirm) {
              let payload = {
                id: this.currentProject.id,
                project_full_code: this.currentProject.project_full_code,
                flow_id: this.currentProject.flow_id,
                node_id: this.currentProject.node_id,
                audit_status: 3,
                audit_comment: "",
              };
              await authApproval(payload);
              uni.showToast({
                title: "审核成功",
              });
              setTimeout(function () {
                uni.hideToast();
                uni.redirectTo({
                  url: "./auth",
                });
              }, 1800);
            }
          },
        });
      } else {
        uni.showModal({
          title: "是否确认拒绝",
          content: "拒绝理由",
          editable: true,
          success: async (res) => {
            if (res.confirm) {
              let payload = {
                id: this.currentProject.id,
                project_full_code: this.currentProject.project_full_code,
                flow_id: this.currentProject.flow_id,
                node_id: this.currentProject.node_id,
                audit_status: 2,
                audit_comment: res.content,
              };
              await authApproval(payload);
              uni.showToast({
                title: "已拒绝",
              });
              setTimeout(function () {
                uni.hideToast();
                uni.redirectTo({
                  url: "./auth",
                });
              }, 1800);
            }
          },
        });
      }
    },
    getAudits(nodeInfo) {
      switch (nodeInfo.id) {
        case 11:
          return "执行项目经理";
        case 12:
          return "运营经理";
        case 13:
          return "执行项目经理";
        case 14:
          return "质保经理";
        default:
          return (nodeInfo.NodeAudits || [])
            .map((item) => item.AuthorRoleInfo.Name)
            .join("，");
      }
    },
    canEdit(index) {
      let {
        audit_status,
        project_status,
        author,
        LeaderId,
        opt_manager_id,
        wty_manager_id,
      } = this.currentProject;
      //audit_status: 0未提审1审核中2审核拒绝3审核通过
      //project_status: 0售前1执行2转运营3转质保
      switch (index) {
        //编辑删除提审
        case 0:
          //售前阶段，未提审/审核被拒，创建人/管理员
          return (
            project_status == 0 &&
            (audit_status == 0 || audit_status == 2) &&
            (this.user.ID == author || this.user.IsSuper)
          );
        //成员管理
        case 1:
          //售前/执行/运营/质保，审核通过，项目经理/管理员
          let manager;
          switch (project_status) {
            case 0:
              manager == author;
              break;
            case 1:
              manager == LeaderId;
              break;
            case 2:
              manager == LeaderId || manager == opt_manager_id;
              break;
            case 3:
              manager == LeaderId || manager == wty_manager_id;
              break;
          }
          return (
            audit_status == 3 && (this.user.ID == manager || this.user.IsSuper)
          );
        //转执行
        case 2:
          //售前，审核通过，售前经理/管理员
          return (
            project_status == 0 &&
            audit_status == 3 &&
            (this.user.ID == author || this.user.IsSuper)
          );
        //转质保运营
        case 3:
          //执行，审核通过，执行经理/管理员
          return (
            project_status == 1 &&
            audit_status == 3 &&
            (this.user.ID == LeaderId || this.user.IsSuper)
          );
      }
    },
    onEdit() {
      uni.redirectTo({
        url: `./add?project_id=${this.currentProject.id}`,
      });
    },
    onDelete() {
      uni.showModal({
        title: "删除项目",
        content: "是否确认删除该项目",
        confirmText: "删除",
        confirmColor: "#ff7875",
        success: async (res) => {
          if (res.confirm) {
            await deleteApproval(this.currentProject);
            uni.showToast({
              title: "删除成功",
            });
            setTimeout(function () {
              uni.hideToast();
              uni.redirectTo({
                url: "./list",
              });
            }, 1800);
          }
        },
      });
    },
    onSubmitAuth() {
      uni.showModal({
        title: "提交审核",
        content: "是否确认提交审核",
        confirmText: "提审",
        success: async (res) => {
          if (res.confirm) {
            let payload = {
              id: this.currentProject.id,
              flow_id: this.currentProject.flow_id,
              node_id: this.currentProject.node_id,
            };
            await submitAudit(payload);
            uni.showToast({
              title: "提审成功",
            });
            setTimeout(function () {
              uni.hideToast();
              uni.redirectTo({
                url: "./list",
              });
            }, 1800);
          }
        },
      });
    },
    onMember() {
      uni.navigateTo({
        url: "./member",
      });
    },
    changeManager(e) {
      if (e.detail.value.length > 0)
        this.formData.manager = e.detail.value[e.detail.value.length - 1].value;
      else this.formData.manager = "";
    },
    onExecute() {
      this.$refs.exePopup.open();
    },
    changeContract(e) {
      this.formData.contract = e.detail.value;
    },
    async submitExecute() {
      this.$refs.exe.validate(async (err) => {
        if (!err) {
          const [dep_id, manager_id] = this.formData.manager.split("-");
          let payload = {
            project_code_id: this.currentProject.id,
            with_contract: Number(this.formData.contract),
            dep_id: Number(dep_id),
            exe_manager_id: Number(manager_id),
          };
          await startExecution(payload);
          this.$refs.exePopup.close();
          uni.showToast({
            title: "转执行送审成功",
          });
          setTimeout(function () {
            uni.hideToast();
            uni.redirectTo({
              url: "./list",
            });
          }, 1800);
        }
      });
    },
    onWarranty() {
      this.$refs.wtyPopup.open();
    },
    async submitWarranty() {
      this.$refs.wty.validate(async (err) => {
        if (!err) {
          const [dep_id, manager_id] = this.formData.manager.split("-");
          let payload = {
            project_code_id: this.currentProject.id,
            dep_id: Number(dep_id),
            wty_manager_id: Number(manager_id),
          };
          await startWarranty(payload);
          this.$refs.wtyPopup.close();
          uni.showToast({
            title: "转质保送审成功",
          });
          setTimeout(function () {
            uni.hideToast();
            uni.redirectTo({
              url: "./list",
            });
          }, 1800);
        }
      });
    },
    onOperate() {
      this.$refs.optPopup.open();
    },
    async submitOperate() {
      this.$refs.opt.validate(async (err) => {
        if (!err) {
          const [dep_id, manager_id] = this.formData.manager.split("-");
          let payload = {
            project_code_id: this.currentProject.id,
            dep_id: Number(dep_id),
            opt_manager_id: Number(manager_id),
          };
          await startOperate(payload);
          this.$refs.optPopup.close();
          uni.showToast({
            title: "转运营送审成功",
          });
          setTimeout(function () {
            uni.hideToast();
            uni.redirectTo({
              url: "./list",
            });
          }, 1800);
        }
      });
    },
    onCancel() {
      this.$refs.exePopup.close();
      this.$refs.wtyPopup.close();
      this.$refs.optPopup.close();
      this.formData = {
        manager: "",
        contract: null,
      };
    },
  },
};
</script>

<style lang="less" scoped>
.content {
  display: flex;
  flex-wrap: wrap;
}
.main {
  width: 100%;
  padding-bottom: 60px;
}
.title {
  width: 100%;
  padding: 0 20px 20px 20px;
  font: 24px bold;
}
.list {
  margin: 0 10% 20px 10%;
}
.detail {
  width: 100%;
  padding: 15px 0;
  font-size: 18px;
  display: flex;
  justify-items: space-between;
  .subTitle {
    width: 30%;
  }
  .detailContent {
    width: 70%;
  }
}
.select {
  width: 100%;
  height: 72rpx;
  line-height: 70rpx;
  border: 1px solid #666;
  padding-left: 20rpx;
}
::v-deep {
  .uni-steps__column-title {
    font-size: 18px;
    line-height: 24px;
  }
  .uni-steps__column-desc {
    font-size: 14px;
    line-height: 18px;
  }
}

.editBtns {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
  margin: 0 5%;
  .edit {
    width: 30%;
    margin-bottom: 20px;
    font-size: 16px;
    text-align: center;
  }
}

.group {
  width: 100%;
  display: flex;
  position: fixed;
  flex-wrap: wrap;
  justify-content: flex-start;
  bottom: 0;
  left: 0;
  .commit {
    width: 50%;
    border-radius: 0;
    margin: inherit;
  }
}

.depSelect {
  width: 200px;
}
</style>
