<template>
  <div class="sellAfterApplyDetail pagePadding">
    <div style="width: 100%" v-if="powers.some((i) => i == '007')">
      <el-tabs v-model="activeTabs">
        <el-tab-pane label="业务详情" name="1">
          <el-collapse v-model="activeNames" style="margin: -18px 0 0 0">
            <el-collapse-item title="售后申请详情" name="1">
              <show-data-table
                :newTime="newTime"
                v-if="newTime !== ''"
                :sitem="sitem"
                :columns="sellshowColumns"
              >
                <template slot="status">
                  <el-tag
                    :size="'mini'"
                    :type="sitem.status == '0' ? 'warning' : ''"
                    v-text="
                      (
                        statusOptions.find(
                          (item) => String(item.id) === String(sitem.status)
                        ) || {}
                      ).label || '--'
                    "
                  ></el-tag>
                </template>

                <template slot="returnWsm">
                  <span>{{ sitem.wsm_name }}</span>
                  <el-popover placement="top" width="400" trigger="hover">
                    <ul>
                      <li><h3>退货仓库</h3></li>
                      <li>
                        <span>编码:</span><span>{{ sitem.wsm_code }}</span>
                      </li>
                      <li>
                        <span>名称:</span><span>{{ sitem.wsm_name }}</span>
                      </li>
                      <li>
                        <span>所在供应商编码:</span
                        ><span>{{ sitem.wsm_supplierNo }}</span>
                      </li>
                      <li>
                        <span>所在供应商名称:</span><span>{{ sitem.wsm_supplier }}</span>
                      </li>
                    </ul>
                    <i slot="reference" class="el-icon-warning-outline fr" />
                  </el-popover>
                </template>

                <template slot="order_type">
                  <el-tag
                    :size="'mini'"
                    v-text="
                      (
                        xs_order_type_options.find(
                          (item) => item.id == sitem.order_type
                        ) || {}
                      ).label || '--'
                    "
                  ></el-tag>
                </template>
                <template slot="is_receive">
                  <el-tag :size="'mini'" :type="''">{{
                    sitem.is_receive + "" === "1"
                      ? "销售订单退货，采购订单也退货"
                      : sitem.is_receive + "" === "0"
                      ? "采购订单不退货(货物已丢失，且无法找回，由业务公司承担)"
                      : "--"
                  }}</el-tag>
                </template>
                <template slot="except_code">
                  <el-tag
                    :size="'mini'"
                    v-text="
                      (
                        expect_options.find((item) => item.value == sitem.except_code) ||
                        {}
                      ).label || '--'
                    "
                  ></el-tag>
                </template>

                <template slot="error_img">
                  <img
                    class="fl hover"
                    style="width: 23px; height: 23px; margin: 0 5px 0 0"
                    v-viewer
                    v-for="(si, i) in sitem.error_img"
                    :src="si"
                    :key="si + i"
                  />
                </template>
              </show-data-table>
            </el-collapse-item>
            <el-collapse-item title="商品信息" name="2">
              <show-goods-data-table
                :newTime="newTime"
                v-if="newTime !== '' && sitem"
                :type="sitem.order_type"
                :skucode="sitem.skuCode"
                :spucode="sitem.good_code"
              />
            </el-collapse-item>
            <el-collapse-item
              name="5"
              title="供应商审核"
              v-if="isHasPermission({ status: '9', process: '9' })"
            >
              <supplier-exam :sitem="sitem" @changeStatus="handleSupplierExam" />
            </el-collapse-item>
            <el-collapse-item
              name="7"
              title="业务公司修改,待供应商确认"
              v-if="isHasPermission({ status: '10', process: '10' })"
            >
              <supplier-confrim :sitem="sitem" @changeStatus="handleSupplierConfirm" />
            </el-collapse-item>
          </el-collapse>
        </el-tab-pane>

        <el-tab-pane label="审批记录" name="2">
          <process-time-line
            v-if="newTime !== ''"
            :newTime="newTime"
            :type="'SHD'"
            :orderCode="orderCode"
          />
        </el-tab-pane>

        <el-tab-pane label="流程图(按执行角色区分)" name="4" style="width: 100%">
          <img src="~@/assets/afterSale.png" />
        </el-tab-pane>
      </el-tabs>
      <open-msg
        :num="10"
        :title="'结算系统中已参与了业务，请解除后申请：'"
        :show-model="showModel1"
        :msg="msg"
        @refresh="showModel1 = false"
        @cancel="showModel1 = false"
      />
    </div>
    <div v-else>
      <no-auth></no-auth>
    </div>
  </div>
</template>
<script>
import mixinPage from "@/mixins/elPaginationHandle";
import resToken from "@/mixins/resToken";
import asyncRequest from "@/apis/service/supplierSellOut/supplierSellAfterApply";
import { sellshowColumns } from "./columns";
import purchaseExam from "./components/purchase_exam";
import SupplierExam from "./components/supplier_exam.vue";
import { xs_order_type_options } from "@/assets/js/statusList";
import WaitReturn from "./components/wait-return.vue";
import SupplierConfrim from "./components/supplier-confirm.vue";
import SetWorkOrder from "./components/set-work-order.vue";
import WaitStockman from "./components/wait-stockman.vue";
import { mapGetters } from "vuex";

export default {
  name: "sellAfterApplyDetail",
  mixins: [mixinPage, resToken],
  components: {
    WaitReturn,
    SupplierExam,
    purchaseExam,
    SupplierConfrim,
    SetWorkOrder,
    WaitStockman,
  },
  computed: {
    ...mapGetters(["isSuppertube"]),
    powers() {
      const tran =
        this.$store.getters.btnList.find(
          (item) => item.menu_route == "supplierSellAfterApplyDetail"
        ) || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
    ppowers() {
      const tran =
        this.$store.getters.roleProcess.find((i) => i.process_type === "SHD") || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },
  data() {
    return {
      showModel1: false,
      msg: "",
      xs_order_type_options,
      activeTabs: "1",
      expect_options: [],
      expect_options1: [
        {
          value: "1",
          label: "退货",
        },
        {
          value: "2",
          label: "换货",
        },
      ],
      expect_options0: [
        {
          value: "1",
          label: "退货",
        },
        {
          value: "2",
          label: "补发",
        },
      ],
      activeNames: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
      status: "", //存储详情接口状态
      statusList: [],
      sellshowColumns: sellshowColumns,
      sitem: null,
      newTime: "",
      loading: false,
      // 收到货状态
      statusOptions: [
        { id: "1", label: "待业务审核" },
        { id: "9", label: "供应商审核" },
        { id: "2", label: "供应商驳回,待采购审核" }, //  id: "2", label: "供应商驳回,待供应商负责人审核" },
        { id: "10", label: "业务公司修改，待供应商确认" },
        { id: "11", label: "待设置工单" }, //已收到货才有
        { id: "4", label: "待客户退货" }, //已收到货才有
        { id: "12", label: "待库管收货" }, //已收到货才有
        { id: "5", label: "售后已完成" },
        { id: "6", label: "业务已驳回" },
        { id: "8", label: "申请已取消" },
      ],
      orderCode: "",
      return_code: "",
      code: "",
    };
  },
  mounted() {
    this.code = this.$route.query.id;
    this.initData();
  },
  methods: {
    isHasPermission({ status, process }) {
      return (
        this.sitem &&
        status === String(this.sitem.status) &&
        this.ppowers.includes(process) &&
        !this.isSupertube
      );
    },
    async handleExpress(data) {
      let res = await asyncRequest.express({
        ...data,
        returnCode: this.code,
      });

      if (res && res.code === 0) {
        this.$notify.success({
          title: "修改成功！",
          message: "",
        });
        await this.initData();
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
      }
    },

    async handleSupplierConfirm(data) {
      const params = {
        ...data,
        returnCode: this.code,
      };

      const { is_receive } = this.sitem;

      if (params.status === "4" && String(is_receive) === "0") {
        params.status = "5";
      }

      const { code, message } = await asyncRequest.status(params);

      if (code === 0) {
        this.$notify.success({
          title: "提交成功！",
          message: "",
        });
        await this.initData();
      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else if (code === 1005) {
        this.msg = message;
        this.showModel1 = true;
      } else {
        this.$message.warning(message);
      }
    },
    async handleSupplierExam(data) {
      const params = {
        ...data,
        returnCode: this.code,
      };

      const { is_receive } = this.sitem;

      if (params.status === "4" && String(is_receive) === "0") {
        params.status = "5";
      }

      const { code, message } = await asyncRequest.status(params);

      if (code === 0) {
        this.$notify.success({
          title: "提交成功！",
          message: "",
        });
        await this.initData();
      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else if (code === 1005) {
        this.msg = message;
        this.showModel1 = true;
      } else {
        this.$message.warning(message);
      }
    },
    getNewTime() {
      this.newTime = new Date().valueOf();
    },
    async handlePurchaseConfirm(data) {
      const model = {
        returnCode: this.code,
        ...data,
      };

      let res = await asyncRequest.status(model);
      if (res && res.code === 0) {
        this.$notify.success({
          title: "修改成功！",
          message: "",
        });
        await this.initData();
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
      }
    },
    async statusConfirm(status, message, remark = "") {
      this.$confirm(`确定要${message}？`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          if (status + "" === "-1") {
            await this.deleteById(message);
          } else {
            await this.setstatus(status, message, remark);
          }
        })
        .catch(() => {
          console.log("取消");
        });
    },
    // 点击业务审核的保存按钮
    async examForm(e) {
      if (!this.loading) {
        let type = e.state + "" === "1" ? "9" : "6";
        const { order_type } = this.sitem;
        const isStock = order_type === "1";

        if (isStock && type === "9") type = "2";
        let message = e.state + "" === "1" ? "提交业务审核" : "提交业务审核";
        await this.statusConfirm(type, message, e.remark);
      }
    },
    //
    async setstatus(type, detail, remark = "") {
      const model = {
        remark,
        returnCode: this.code,
        status: type,
      };
      let res = await asyncRequest.status(model);

      if (res && res.code === 0) {
        this.$notify.success({
          title: "修改成功！",
          message: "",
        });
        await this.initData();
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
      }
    },
    hasPermission({ status, process }) {
      console.log(this.sitem);
      return (
        !this.isSupertube &&
        String(this.sitem.status) === status &&
        this.ppowers.includes(process)
      );
    },
    async initData() {
      let model = {
        returnCode: this.code,
      };
      const res = await asyncRequest.detail(model);
      if (res && res.code === 0 && res.data) {
        this.sitem = res.data;
        const { status, can, returnCode } = this.sitem;
        this.status = status;
        this.orderCode = returnCode;
        this.sitem.error_img = this.sitem.error_img.split(",");
        this.expect_options = JSON.parse(
          JSON.stringify(
            this.sitem.is_receive + "" === "1"
              ? this.expect_options1
              : this.expect_options0
          )
        );
        this.getNewTime();
      } else if (res && res.code >= 100 && res.code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(res.message);
      }
    },
  },
};
</script>
