<template>
  <div class="sellReturnDetail 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="0">
              <show-data-table
                style="margin: 0; padding: 0"
                :sitem="sitem"
                v-if="status"
                :columns="showColumns"
              >
                <template slot="status">
                  <el-tag
                    :size="'mini'"
                    v-text="
                      (statusOptions.find((item) => item.value == sitem.status) || {})
                        .label || '--'
                    "
                  ></el-tag>
                </template>

                <template slot="is_addr">
                  <el-tag size="mini">{{
                    sitem.is_addr === "0"
                      ? "无地址退货"
                      : sitem.is_addr === "1"
                      ? "有地址退货"
                      : "--"
                  }}</el-tag>
                </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="supplierName">
                  <span>{{ sitem.supplierName }}</span>
                  <el-popover placement="top" width="300" trigger="hover">
                    <ul>
                      <li>
                        <span>销售方公司编号：</span><span>{{ sitem.supplierNo }}</span>
                      </li>
                    </ul>
                    <i class="el-icon-warning-outline fr" slot="reference"></i>
                  </el-popover>
                </template>
                <template slot="loop_total">
                  <span>供应商负责人共修改供应商审批结果 {{ sitem.loop_total }} 次</span>
                </template>

                <template slot="companyName">
                  <span>{{ sitem.customer_name }}</span>
                  <el-popover placement="top" width="300" trigger="hover">
                    <ul>
                      <li>
                        <span>购买方公司编号：</span
                        ><span>{{ sitem.customer_code }}</span>
                      </li>
                    </ul>
                    <i class="el-icon-warning-outline fr" slot="reference"></i>
                  </el-popover>
                </template>
                <template slot="is_active">
                  <span
                    v-if="sitem.order_type + '' === '1' || sitem.order_type + '' === '2'"
                    ><span
                      >{{ sitem.is_activity + "" === "1" ? "参与活动" : "不参与活动" }}/{{
                        sitem.good_type
                      }}</span
                    ></span
                  >
                  <span v-else>--</span>
                </template>
                <template slot="send_type">
                  <el-tag :size="'mini'">{{
                    sitem.send_type + "" === "1"
                      ? "有地址下单"
                      : sitem.send_type + "" === "2"
                      ? "无地址下单"
                      : "--"
                  }}</el-tag>
                </template>
                <template slot="addrinfo">
                  <div
                    v-if="sitem && sitem.addrinfo && sitem.addrinfo.length > 0"
                    style="padding: 2px 8px 0 0"
                  >
                    <el-table
                      :data="sitem.addrinfo"
                      border
                      :size="'mini'"
                      row-key="key"
                      max-height="300px"
                    >
                      <el-table-column
                        label="发货单号"
                        prop="outCode"
                        width="160"
                        show-overflow-tooltip
                      />
                      <el-table-column
                        label="收货总数量"
                        prop="receipt_quantity"
                        width="110"
                        show-overflow-tooltip
                      />
                      <el-table-column
                        label="未发货数量"
                        prop="addr_wsend"
                        width="110"
                        show-overflow-tooltip
                      />
                      <el-table-column
                        label="已发货数量"
                        prop="addr_send"
                        width="110"
                        show-overflow-tooltip
                      />
                      <el-table-column
                        label="退货数量"
                        prop="return_num"
                        width="110"
                        show-overflow-tooltip
                      />

                      <el-table-column
                        label="收货人-联系电话-地址"
                        min-width="220"
                        show-overflow-tooltip
                      >
                        <template slot-scope="scope">
                          {{ scope.row.contactor }}-{{ scope.row.mobile }}-{{ scope.row.addr_info }}{{ scope.row.addr }}
                        </template>
                      </el-table-column>
                    </el-table>
                  </div>
                  <span v-else>--</span>
                </template>
              </show-data-table>
            </el-collapse-item>

            <el-collapse-item
              title="申请退货的发货单"
              name="8"
              v-if="sitem && sitem.is_addr === '1'"
            >
              <child-list
                ref="childListRef"
                :sitem="sitem"
                @getCurrentWorkOrderCount="
                  (_currentOrderWork) => (currentWorkOrder = _currentOrderWork)
                "
                @getWorkOrderCount="
                  (_workOrderCount) => (workOrderCount = _workOrderCount)
                "
                @getSendInfoFirst="onGetSendInfoFirst"
              />
            </el-collapse-item>

            <el-collapse-item
              title="待业务审核"
              name="3"
              v-if="isHasPermission({ status: '1', process: '1' })"
            >
              <exam-form
                v-if="newTime"
                :statusList="statusList"
                :newTime="newTime"
                :disabled="false"
                :isMust="false"
                @searchChange="examForm"
              />
            </el-collapse-item>
            <el-collapse-item
              title="待供应商审核"
              name="4"
              v-if="
                isHasPermission({ status: '9', process: '9' }) && String(sitem.has_account) === '0'
              "
            >
              <exam-form
                v-if="newTime"
                :statusList="statusList"
                :newTime="newTime"
                :disabled="false"
                :isMust="false"
                @searchChange="examForm_supplier"
              />
            </el-collapse-item>
            <el-collapse-item
              title="供应商已驳回,待采购审核"
              name="5"
              v-if="isHasPermission({ status: '8', process: '8' })"
            >
              <approval-results :sitem="sitem" @changeStatus="handlePurchaseExam" />
            </el-collapse-item>

            <el-collapse-item
              title="业务公司修改，待供应商确认"
              name="6"
              v-if="
                isHasPermission({ status: '10', process: '10' }) &&
                String(sitem.has_account) === '0'
              "
            >
              <exam-form
                v-if="newTime"
                :statusList="statusList"
                :newTime="newTime"
                :disabled="false"
                :isMust="false"
                @searchChange="handleSupplierConfirm"
              />
            </el-collapse-item>

            <el-collapse-item
              title="待设置工单"
              name="7"
              v-if="isHasPermission({ status: '11', process: '11' })"
            >
              <set-work-order
                :sitem="sitem"
                :currentWorkOrder="currentWorkOrder"
                :workOrderCount="workOrderCount"
                :outItem="outItem"
                @reload="handleReload"
              />
            </el-collapse-item>

            <el-collapse-item title="商品信息" name="2">
              <show-goods-data-table
                :newTime="newTime"
                v-if="newTime !== ''"
                :type="sitem && sitem.order_type ? sitem.order_type : ''"
                :skucode="sitem.skuCode"
                :spucode="sitem.good_code"
                :iscgd="false"
              />
            </el-collapse-item>
          </el-collapse>
        </el-tab-pane>
        <el-tab-pane label="审批记录" name="2">
          <process-time-line
            v-if="newTime !== ''"
            :newTime="newTime"
            :type="'XSTHD'"
            :orderCode="queryId"
          />
        </el-tab-pane>

        <!-- <el-tab-pane label="流程图" name="3">
          <flow-chart ref="flowChart" />
        </el-tab-pane> -->

        <el-tab-pane label="流程图(按执行角色区分)" name="4">
          <img src="~@/assets/beforeSale.jpg" style="width: 100%" />
        </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/sellOut/sellReturn";
import comExamForm from "./components/comExamForm";
import ApprovalResults from "./components/approval-results.vue";
import { showColumns } from "./components/ShowDataTableColumns";
import { xs_order_type_options } from "@/assets/js/statusList";
import SetWorkOrder from "./components/set-work-order.vue";
import { mapGetters } from "vuex";
import ShowWorkOrder from "./components/show-work-order.vue";
import childList from "./components/child-list.vue";
export default {
  name: "sellReturnDetail",
  mixins: [mixinPage, resToken],
  components: {
    comExamForm,
    ApprovalResults,
    SetWorkOrder,
    ShowWorkOrder,
    childList,
  },
  computed: {
    ...mapGetters(["isSupertube"]),
    powers() {
      const tran =
        this.$store.getters.btnList.find(
          (item) => item.menu_route == "sellReturnDetail"
        ) || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
    ppowers() {
      const tran =
        this.$store.getters.roleProcess.find((i) => i.process_type === "XSTHD") || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },
  data() {
    return {
      showModel1: false,
      msg: "",
      activeTabs: "1",
      showColumns: showColumns,
      workOrderCount: "",
      currentWorkOrder: "",
      outItem: {},
      statusOptions: [
        { value: "1", label: "待业务审批" },
        { value: "4", label: "退货完成" },
        { value: "5", label: "业务驳回" },
        { value: "8", label: "供应商已驳回,待采购审核" },
        { value: "9", label: "待供应商审核" },
        { value: "10", label: "业务公司修改,待供应商确认" },
        { value: "11", label: "待设置工单" },
        { value: "12", label: "待库管收货" },
        { value: "13", label: "已取消申请" },
      ],
      xs_order_type_options,
      sitem: null, //传给组件
      activeNames: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "10"],
      status: "", //存储详情接口状态
      statusList: [
        {
          value: "1",
          label: "待验货",
        },
        {
          value: "2",
          label: "待验货审核",
        },
        {
          value: "3",
          label: "待业务审核",
        },
      ],
      newTime: "",
      loading: false,
      is_stock: "",
      queryId: "",
    };
  },
  mounted() {
    this.queryId = this.$route.query.id;
    this.initData();
    this.renderChart();
  },
  methods: {
    createNodes() {
      return [
        {
          id: "0",
          text: "创建售前退货申请",
          type: "NormalTask",
          x: 650,
          y: 100,
          properties: {},
        },
        {
          id: "1",
          text: "待业务审核",
          type: "NormalTask",
          x: 650,
          y: 200,
          properties: {},
        },
        {
          id: "9",
          text: "待供应商审核",
          type: "NormalTask",
          x: 650,
          y: 300,
          properties: {},
        },
        {
          id: "8",
          text: "供应商已驳回," + "\n" + "待采购审核",
          type: "NormalTask",
          x: 650,
          y: 400,
          properties: {},
        },
        {
          id: "10",
          text: "业务公司修改," + "\n" + "待供应商确认",
          type: "NormalTask",
          x: 650,
          y: 500,
          properties: {},
        },
        { id: "4", text: "完成退货", type: "NormalTask", x: 650, y: 600, properties: {} },
        {
          id: "11",
          text: "待设置退货工单",
          type: "NormalTask",
          x: 350,
          y: 400,
          properties: {},
        },
        {
          id: "12",
          text: "待库管收货",
          type: "NormalTask",
          x: 350,
          y: 500,
          properties: {},
        },
      ];
    },
    createEdges() {
      return [
        { sourceNodeId: "0", targetNodeId: "1", isHitable: false, type: "dashe-edge" },
        { sourceNodeId: "1", targetNodeId: "9", isHitable: false, type: "dashe-edge" },
        { sourceNodeId: "9", targetNodeId: "8", isHitable: false, type: "dashe-edge" },
        { sourceNodeId: "8", targetNodeId: "11", isHitable: false, type: "dashe-edge" },
        { sourceNodeId: "11", targetNodeId: "12", isHitable: false, type: "dashe-edge" },
        { sourceNodeId: "10", targetNodeId: "4", isHitable: false, type: "dashe-edge" },
        { sourceNodeId: "8", targetNodeId: "10", isHitable: false, type: "dashe-edge" },
        { sourceNodeId: "10", targetNodeId: "8", isHitable: false, type: "dashe-edge" },
        { sourceNodeId: "11", targetNodeId: "12", isHitable: false, type: "dashe-edge" },
        { sourceNodeId: "12", targetNodeId: "4", isHitable: false, type: "dashe-edge" },
      ];
    },
    renderChart() {
      this.$refs.flowChart.render({
        nodes: this.createNodes(),
        edges: this.createEdges(),
      });
    },
    onGetSendInfoFirst(item) {
      this.outItem = item;
    },
    async statusConfirm(status, message, remark) {
      this.$confirm(`确定要${message}？`, {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await this.setstatus(status, message, remark);
        })
        .catch(() => {
          console.log("取消");
        });
    },
    async handlePurchaseExam(data) {
      // 是否为库存品
      const isStock = this.sitem.order_type === "1";

      // 非库存品且审批通过 = 完成退货
      if(data.status === "11" && !isStock){
        data.status = "4";
      }

      let _model = {
        returnCode: this.queryId,
        ...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);
      }
    },
    getNewTime() {
      this.newTime = new Date().valueOf();
    },
    async handleReload() {
      this.initData();
      /*  重新获取最第一条退货单 **/
      this.$refs.childListRef && this.$refs.childListRef.searchList();
    },
    //供应商确认
    async handleSupplierConfirm(e) {
      if (!this.loading) {
        let type = e.state + "" === "1" ? "4" : "8";
        let message = e.state + "" === "1" ? "提交审核结果" : "提交审核结果";
        await this.statusConfirm(type, message, e.remark);
      }
    },
    // 点击业务审核的保存按钮
    async examForm(e) {
      if (!this.loading) {
        let type = e.state + "" === "1" ? "9" : "5";
        let message = e.state + "" === "1" ? "提交审核结果" : "提交审核结果";
        await this.statusConfirm(type, message, e.remark);
      }
    },
    async examForm_supplier(e) {
      if (!this.loading) {
        let type = e.state + "" === "1" ? "4" : "8";
        let message = e.state + "" === "1" ? "提交审核结果" : "提交审核结果";
        await this.statusConfirm(type, message, e.remark);
      }
    },
    // 点击采购主管审核的保存按钮
    async dirExamForm(e) {
      if (!this.loading) {
        let type = e.state + "" === "1" ? "4" : "8";
        let message = e.state + "" === "1" ? "提交审核结果" : "提交审核结果";
        await this.statusConfirm(type, message, e.remark);
      }
    },
    async setstatus(type, msg, remark = "") {
      let _model = {
        returnCode: this.queryId,
        status: type,
        remark: remark,
      };
      const { code, data, message } = await asyncRequest.status(_model);
      if (code === 0) {
        this.$notify.success({
          title: msg + "成功！",
          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);
      }
    },

    isHasPermission({ status, process }) {
      return (
        this.sitem &&
        String(this.sitem.status) === status &&
        this.ppowers.includes(process) &&
        !this.isSupertube
      );
    },

    async initData() {
      const { code, data, message } = await asyncRequest.detail({
        returnCode: this.queryId,
      });

      if (code === 0) {
        const { is_stock, status } = data;
        this.is_stock = is_stock;
        this.status = status;
        this.sitem = data;
        this.getNewTime();
      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else {
        this.$message.warning(message);
      }
    },
  },
};
</script>
