<template>
  <view>
    <view class="card-wrapper" v-if="showEdit()">
      <uni-card title="操作">
        <view class="editBtns" slot="actions">
          <view class="edit" v-if="!isDetail" @click="onClickProject">
            项目详情
          </view>
          <view class="edit" v-if="canEdit(0)" @click="onEdit">编辑</view>
          <view class="edit" v-if="canEdit(0)" @click="onDelete">删除</view>
          <view class="edit" @click="onDaily">项目日志</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 class="edit" v-if="canAuth()" @click="onHandleAudit(1)">
            审核通过
          </view>
          <view class="edit" v-if="canAuth()" @click="onHandleAudit(0)">
            审核拒绝
          </view>
          <view class="edit empty">
          </view>
          <view class="edit empty">
          </view>
        </view>
      </uni-card>
    </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 {
  deleteApproval,
  submitAudit,
  startExecution,
  startWarranty,
  startOperate,
  authApproval,
} from "@/services/project";
export default {
  props: ["project", "user", "auth", "flowList", "depRole", "isDetail"],
  computed: {
    ...mapState(["depUserTree", "showSearch"]),
  },
  data() {
    return {
      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: "请选择运营经理" }],
        },
      },
    };
  },
  methods: {
    showEdit() {
      let toRet =
        !this.isDetail ||
        this.canEdit(0) ||
        this.canEdit(1) ||
        this.canEdit(2) ||
        this.canEdit(3) ||
        this.canAuth();
      this.$emit("canEdit", toRet);
      return toRet;
    },
    onDaily() {
      uni.navigateTo({
        url: `/pages/daily/projectDaily?project_id=${this.project.id}`,
      });
    },
    hideHelper() {
      setTimeout(() => {
        uni.hideToast();
        if (this.isDetail) uni.navigateBack();
        else location.reload();
      }, 1800);
    },
    async onClickProject() {
      await this.$store.commit("setCurrentProject", this.project);
      uni.navigateTo({
        url: `./detail?id=${this.project.id}${this.auth ? "&auth=true" : ""}`,
      });
    },
    canEdit(index) {
      if (this.auth) return false;
      let {
        audit_status,
        project_status,
        author,
        LeaderId,
        opt_manager_id,
        wty_manager_id,
      } = this.project;
      //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 = this.user.ID == author;
              break;
            case 1:
              manager = this.user.ID == LeaderId;
              break;
            case 2:
              manager =
                this.user.ID == LeaderId || this.user.ID == opt_manager_id;
              break;
            case 3:
              manager =
                this.user.ID == LeaderId || this.user.ID == wty_manager_id;
              break;
          }
          return audit_status == 3 && (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)
          );
      }
    },
    async onEdit() {
      await this.$store.commit("setCurrentProject", this.project);
      uni.navigateTo({
        url: `./add?project_id=${this.project.id}`,
      });
    },
    onDelete() {
      uni.showModal({
        title: "删除项目",
        content: "是否确认删除该项目",
        confirmText: "删除",
        confirmColor: "#ff7875",
        success: async (res) => {
          if (res.confirm) {
            await deleteApproval(this.project);
            uni.showToast({
              title: "删除成功",
            });
            this.hideHelper();
          }
        },
      });
    },
    onSubmitAuth() {
      uni.showModal({
        title: "提交审核",
        content: "是否确认提交审核",
        confirmText: "提审",
        success: async (res) => {
          if (res.confirm) {
            let payload = {
              id: this.project.id,
              flow_id: this.project.flow_id,
              node_id: this.project.node_id,
            };
            await submitAudit(payload);
            uni.showToast({
              title: "提审成功",
            });
            this.hideHelper();
          }
        },
      });
    },
    async onMember() {
      await this.$store.commit("setCurrentProject", this.project);
      uni.navigateTo({
        url: "./member",
      });
    },
    async submitHelper(payload = {}, type) {
      const [dep_id, manager_id] = this.formData.manager.split("-");
      payload = {
        ...payload,
        project_code_id: this.project.id,
        dep_id: Number(dep_id),
      };
      switch (type) {
        case "exe":
          await startExecution(payload);
          this.$refs.exePopup.close();
          uni.showToast({
            title: "转执行送审成功",
          });
          break;
        case "wty":
          await startWarranty(payload);
          this.$refs.wtyPopup.close();
          uni.showToast({
            title: "转质保送审成功",
          });
          break;
        case "opt":
          await startOperate(payload);
          this.$refs.optPopup.close();
          uni.showToast({
            title: "转运营送审成功",
          });
          break;
      }
      this.hideHelper();
    },
    changeManager(e) {
      if (e.detail.value.length > 0)
        this.formData.manager = e.detail.value[e.detail.value.length - 1].value;
      else this.formData.manager = "";
    },
    async onExecute() {
      await this.$store.commit("setShowSearch", false);
      this.$refs.exePopup.open();
    },
    changeContract(e) {
      this.formData.contract = e.detail.value;
    },
    submitExecute() {
      this.$refs.exe.validate((err) => {
        if (!err) {
          const [dep_id, manager_id] = this.formData.manager.split("-");
          let payload = {
            with_contract: Number(this.formData.contract),
            exe_manager_id: Number(manager_id),
          };
          this.submitHelper(payload, "exe");
        }
      });
    },
    async onWarranty() {
      await this.$store.commit("setShowSearch", false);
      this.$refs.wtyPopup.open();
    },
    submitWarranty() {
      this.$refs.wty.validate((err) => {
        if (!err) {
          const [dep_id, manager_id] = this.formData.manager.split("-");
          let payload = {
            wty_manager_id: Number(manager_id),
          };
          this.submitHelper(payload, "wty");
        }
      });
    },
    async onOperate() {
      await this.$store.commit("setShowSearch", false);
      this.$refs.optPopup.open();
    },
    submitOperate() {
      this.$refs.opt.validate((err) => {
        if (!err) {
          const [dep_id, manager_id] = this.formData.manager.split("-");
          let payload = {
            opt_manager_id: Number(manager_id),
          };
          this.submitHelper(payload, "opt");
        }
      });
    },
    async onCancel() {
      await this.$store.commit("setShowSearch", true);
      this.$refs.exePopup.close();
      this.$refs.wtyPopup.close();
      this.$refs.optPopup.close();
      this.formData = {
        manager: "",
        contract: null,
      };
    },
    canAuth() {
      if (!this.auth) return false;
      let { NodeInfo, audit_status, project_status } = this.project;
      if (!NodeInfo || this.flowList.length == 0 || this.depRole.length == 0)
        return false;
      if (audit_status != 1) return false;

      if (project_status == 2)
        return this.project.opt_manager_id == this.user.ID;
      if (project_status == 3)
        return this.project.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.project.id,
                project_full_code: this.project.project_full_code,
                flow_id: this.project.flow_id,
                node_id: this.project.node_id,
                audit_status: 3,
                audit_comment: "",
              };
              await authApproval(payload);
              uni.showToast({
                title: "审核成功",
              });
              this.hideHelper();
            }
          },
        });
      } else {
        uni.showModal({
          title: "是否确认拒绝",
          content: "拒绝理由",
          editable: true,
          success: async (res) => {
            if (res.confirm) {
              let payload = {
                id: this.project.id,
                project_full_code: this.project.project_full_code,
                flow_id: this.project.flow_id,
                node_id: this.project.node_id,
                audit_status: 2,
                audit_comment: res.content,
              };
              await authApproval(payload);
              uni.showToast({
                title: "已拒绝",
              });
              this.hideHelper();
            }
          },
        });
      }
    },
  },
};
</script>

<style lang="less" scoped>
.editBtns {
  display: flex;
  justify-content: space-around;
  flex-wrap: wrap;
  margin: 0 5%;
  .edit {
    width: 30%;
    margin-bottom: 20px;
    font-size: 28rpx;
    text-align: center;
    border-radius: 10rpx;
    box-shadow: 0 2rpx 2rpx #666;
    &.empty {
      visibility: hidden;
      height: 1;
      margin: 0;
      opacity: 0;
    }
  }
}

.card-wrapper {
  padding-bottom: 60rpx;
}

.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;
  }
}
.depSelect {
  width: 200px;
}
</style>
