<template>
  <div class="outOrderTable">
    <el-table
      ref="addrForm"
      :data="tableData"
      border
      :size="'mini'"
      style="width: 100%"
      row-key="key"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="42"> </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="outCode"
        label="发货申请单号"
        width="160"
      />

      <el-table-column show-overflow-tooltip prop="send_status" label="状态" width="105">
        <template slot-scope="scope">
          <el-tag
            :size="tablebtnSize"
            :type="scope.row.status == '0' ? 'warning' : ''"
            v-text="
              (statusOptions.find((item) => item.id == scope.row.status) || {}).label ||
              '--'
            "
          ></el-tag>
        </template>
      </el-table-column>

      <el-table-column
        show-overflow-tooltip
        prop="send_num"
        label="发货数量"
        width="80"
      />
      <el-table-column show-overflow-tooltip prop="contactor" label="联系人" width="80" />
      <el-table-column show-overflow-tooltip prop="mobile" label="联系电话" width="110" />
      <el-table-column show-overflow-tooltip prop="addr" label="收货地址" min-width="170">
        <template slot-scope="scope">
          {{ scope.row.addr_info }}{{ scope.row.addr }}
        </template>
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="post_name"
        label="物流公司"
        width="160"
      />
      <el-table-column
        show-overflow-tooltip
        prop="post_code"
        label="物流单号"
        width="160"
      />
      <el-table-column
        show-overflow-tooltip
        prop="sendtime"
        label="发货时间"
        width="145"
      />
      <el-table-column fixed="right" width="150">
        <template slot="header" slot-scope="scope">
          <span v-if="addr_res + '' === '0'">操作</span>
          <el-tooltip
            style="margin: 3px 0 0 8px"
            effect="dark"
            class="fr"
            v-if="addr_res + '' !== '0' && powers.some((i) => i == '048')"
            content="添加"
            placement="top"
          >
            <i
              class="el-icon-circle-plus-outline tb-icon"
              style="color: #6954f0; magin: 0 0 0 10px"
              @click="openHouseModal()"
            ></i>
          </el-tooltip>
          <el-tooltip
            class="fr"
            style="margin: 3px 0 0 8px"
            effect="dark"
            v-if="addr_res + '' !== '0' && powers.some((i) => i == '048')"
            content="导入收货地址"
            placement="top"
          >
            <i
              class="el-icon-upload2 tb-icon"
              style="color: #6954f0"
              @click="addrmodel = true"
            ></i>
          </el-tooltip>
          <el-tooltip
            class="fr"
            style="margin: 3px 0 0 8px"
            effect="dark"
            v-if="addr_res + '' !== '0' && powers.some((i) => i == '048')"
            content="下载收货地址模板"
            placement="top"
          >
            <a class="downloadAddr" href="./static/收货地址模板.xlsx">
              <i class="el-icon-download tb-icon" style="color: #6954f0; margin: 0"></i>
            </a>
          </el-tooltip>

          <el-tooltip
            style="margin: 3px 0 0 0"
            effect="dark"
            content="退货"
            class="fr"
            v-if="addr_res + '' !== '0' && powers.some((i) => i == '051')"
            placement="top"
          >
            <i
              class="el-icon-delete tb-icon"
              style="color: #6954f0; magin: 0 0 0 10px"
              @click="openModal(0)"
            ></i>
          </el-tooltip>
          <el-tooltip
            effect="dark"
            content="批量退货"
            style="margin: 3px 0 0 8px"
            v-if="batch_num + '' !== '0' && powers.some((i) => i == '051')"
            placement="top"
          >
            <i
              class="el-icon-date tb-icon"
              style="color: #6954f0"
              @click="openModal()"
            ></i>
          </el-tooltip>
          <el-tooltip
            effect="dark"
            content="全部退货"
            style="margin: 3px 0 0 8px"
            v-if="status + '' === '0' && powers.some((i) => i == '051')"
            placement="top"
          >
            <i
              class="el-icon-refresh-left tb-icon"
              style="color: #6954f0"
              @click="openAllModal()"
            ></i>
          </el-tooltip>
        </template>

        <template slot-scope="scope">
          <el-tooltip
            effect="dark"
            content="查看"
            placement="top"
            v-if="powers.some((i) => i == '007')"
          >
            <i
              class="el-icon-view tb-icon"
              @click="routeGoto('sellOutOrderDetail', { id: scope.row.outCode })"
            ></i>
          </el-tooltip>
          <!-- <el-tooltip
            effect="dark"
            content="退货"
            v-if="
              (scope.row.status == '0' || scope.row.status == '1') &&
              powers.some((i) => i == '051')
            "
            placement="top"
          >
            <i class="el-icon-delete tb-icon" @click="openModal(scope.row)"></i>
          </el-tooltip> -->
        </template>
      </el-table-column>
    </el-table>
    <div
      v-if="tableData && tableData.length > 0"
      class="Pagination"
      style="text-align: right; margin-top: 10px"
    >
      <el-pagination
        :current-page="parmValue.page"
        :page-size="parmValue.size"
        :size="'mini'"
        layout="total,  prev, pager, next, jumper"
        :total="pageInfo.total"
        @size-change="page_size_change"
        @current-change="page_curr_change"
      />
    </div>

    <out-order-add-model
      :showModel="modelShowModel"
      :id="modelId"
      :sitem="modelItem"
      @refresh="refresh"
      @cancel="closeModel"
    />
    <in-addr-model
      :show-model="addrmodel"
      @cancel="addrmodel = false"
      @refresh="addrRefresh"
    />

    <add-model
      :id="returnId"
      :sitem="returnItem"
      :show-model="returnModel"
      :is-detail="false"
      @refresh="refresh"
      @cancel="returnModel = false"
    />

    <!-- <add-edit
      :id="modelId"
      :sitem="s_sitem"
      :show-model="showModel"
      :is-detail="isDetail"
      @refresh="searchList"
      @cancel="showModel = false"
    /> -->

    <add-return-all-model
      :id="returnAllId"
      :sitem="returnAllSitem"
      :show-model="returnAllShowModel"
      :is-detail="false"
      @refresh="refresh"
      @cancel="returnAllShowModel = false"
    />
  </div>
</template>
<script>
import mixinPage from "@/mixins/elPaginationHandle";
import resToken from "@/mixins/resToken";
import asyncRequest from "@/apis/service/sellOut/salesOrder/detail";
import outOrderAddModel from "./out-order-add-model";
import addModel from "@/views/sellOut/sellReturn/components/addModel";
import inAddrModel from "@/components/in-addr-model";
import addReturnAllModel from "./addReturnAllModel";
import { mapGetters } from "vuex";

export default {
  name: "salesOrderDetail",
  mixins: [mixinPage, resToken],
  props: ["newTime", "id", "sitem"],
  components: { outOrderAddModel, addModel, inAddrModel, addReturnAllModel },
  watch: {
    newTime: function (val) {
      if (val) {
        this.initForm();
      }
    },
  },
  computed: {
    ...mapGetters(["tablebtnSize", "searchSize", "size"]),

    powers() {
      const tran =
        this.$store.getters.btnList.find(
          (item) => item.menu_route == "salesOrderDetail"
        ) || {};
      const { action } = tran ?? {};
      return action ?? [];
    },
  },

  data() {
    return {
      orderCode: "",
      outCode: "",
      addr_res: 0,
      batch_num: 0,
      addrmodel: false,
      // 状态
      statusOptions: [
        { id: "0", label: "待公司采购" },
        { id: "1", label: "待库管发货" },
        { id: "2", label: "已发货待收货" },
        { id: "3", label: "已收货" },
        { id: "4", label: "已全部退货" },
      ],
      showGoodsModel: false,
      stock_code: "",
      tableData: [],
      loading: false,
      queryId: "",
      status: "",
      showModel: null,
      modelId: "",
      modelItem: null,
      s_sitem: null,
      returnId: "",
      returnItem: null,
      returnModel: false,
      wsend_num: "",
      orderCode: "",
      returnAllId: "",
      returnAllSitem: null,
      returnAllShowModel: false,
      parmValue: {
        order_type: "",
        orderCode: "",
        apply_name: "", //申请人名称
        cgdNo: "",
        start: "",
        end: "",
        // supplierNo: "",
        companyNo: "",
        good_code: "",
        good_name: "",
        outCode: "",
        status: "",
        company_name: "", //申请人部门
        page: 1, // 页码
        size: 15, // 每页显示条数
      },
      pageInfo: {
        size: 15,
        curr: 1,
        total: 0,
      },
      multipleSelection: [],
      resModel: null,
    };
  },
  mounted() {
    this.initForm();
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    closeModel() {
      this.modelId = "";
      this.modelShowModel = false;
    },
    refresh() {
      this.$emit("refresh");
      this.modelId = "";
      this.modelShowModel = false;
    },
    async initForm() {
      this.status = "";
      this.queryId = this.$route.query.id;
      // this.rulesThis = this.rules;
      this.resetForm();
    },
    async resetForm() {
      // 重置
      await this.$nextTick(async () => {
        this.wsend_num = true;
        const { orderCode, status, good_num, addr_sum } = this.sitem;
        this.status = status;
        this.orderCode = orderCode || "";
        this.addr_res = parseInt(good_num) - parseInt(addr_sum);
        if (this.addr_res < 0) {
          this.addr_res = "0";
        }
        // console.log(this.status);
        await this.searchList();
        // this.tableData = JSON.parse(JSON.stringify(addrs));
      });
    },
    // 列表搜索
    async searchList() {
      this.parmValue.orderCode = this.orderCode;
      const { code, data, message } = await asyncRequest.orderOut(this.parmValue);
      if (code === 0) {
        const { list, count } = data;
        this.tableData = list;
        this.pageInfo.total = Number(count);
        this.batch_num = 0;
        this.tableData.forEach((v) => {
          v.good_class = "";
          if (v.can && v.can.length > 0) {
            v.can.forEach((x, i) => {
              v.good_class += i === 0 ? x.name : "/" + x.name;
            });
          }
          if (v.status + "" === "0" || v.status + "" === "1") {
            this.batch_num += parseInt(v.send_num + "");
          }
        });
        console.log(this.batch_num);
      } else if (code >= 100 && code <= 104) {
        await this.logout();
      } else {
        this.tableData = [];
        this.pageInfo.total = 0;
      }
      this.loading = false;
    },
    async addrRefresh(e) {
      if (!this.loading) {
        this.loading = true;
        const { arrive_time, orderCode, wsend_num } = this.sitem;
        const { list } = e;
        console.log(list);
        let t_num = 0,
          add_num = 0;
        let model = {
          arrtime: arrive_time,
          orderCode: orderCode,
          addrlist: [],
        };
        list.forEach((a) => {
          add_num += a.receipt_quantity * 1;
          let item = {
            contactor: a.contactor,
            mobile: a.mobile,
            addr: a.addr,
            addr_code: a.addr_code,
            receipt_quantity: a.receipt_quantity,
          };
          model.addrlist.push(item);
        });
        if (wsend_num * 1 < t_num + add_num) {
          this.$message.warning("导入地址总数量不能大于未发货总数量！");
          this.loading = false;
          return;
        }
        const { code, message } = await asyncRequest.saleaddr(model);
        this.loading = false;
        if (code === 0) {
          this.$notify.success({
            title: "地址导入成功！",
            message: "",
          });
          this.showModelThis = false;
          // 刷新
          this.$emit("refresh");
        } else if (code >= 100 && code <= 104) {
          await this.logout();
        } else {
          this.$message.warning(message);
        }
      }

      // this.tableData = [];
      // this.tableData.push(...list);
    },
    editRow(index) {
      let findex = this.stockForm.good_stock.findIndex((v) => v.edit === true);
      if (findex !== -1) {
        this.$message.warning("当前已有发货仓库信息在编辑，请保存后再试！");
        return;
      } else {
        this.stockForm.good_stock[index].edit = true;
      }
    },

    openHouseModal() {
      this.modelId = "add";
      this.modelItem = this.sitem;
      this.modelShowModel = true;
    },
    openModal(e) {
      if (e === 0) {
        this.resModel = {
          good_num: this.addr_res + "",
          orderCode: this.orderCode,
          return_type: "1",
          remark: "", //退货备注
          errorCode: "", //退货原因
          thnum: this.addr_res + "",
          returnT: this.addr_res + "",
          returnAddr: [],
        };
        this.returnItem = this.resModel;
        this.returnModel = true;
        //  scope.row.outCode
      } else {
        let tol = 0,
          send_num = 0;
        this.multipleSelection.forEach((s) => {
          console.log(parseInt(s.send_num + ""));
          if (!(s.status + "" === "0" || s.status + "" === "1")) {
            tol += parseInt(s.send_num + "");
          } else {
            send_num += parseInt(s.send_num + "");
          }
        });
        console.log(tol, send_num);
        if (this.multipleSelection.length == 0) {
          this.$message.warning("请选择发货申请单！");
        } else if (tol !== 0) {
          this.$message.warning("不能已发货的发货申请单！");
        } else {
          // const { addrid, send_num, outCode } = e;
          this.resModel = {
            good_num: send_num + "",
            orderCode: this.orderCode,
            return_type: "2",
            remark: "", //退货备注
            errorCode: "", //退货原因
            thnum: send_num + "",
            returnT: send_num + "",
            returnAddr: JSON.parse(JSON.stringify(this.multipleSelection)),
          };
          this.returnItem = this.resModel;
          this.returnModel = true;
        }
      }

      console.log(addModel);
    },
    async restSearch() {
      this.parmValue = {
        order_type: "",
        orderCode: "",
        apply_name: "", //申请人名称
        cgdNo: "",
        start: "",
        end: "",
        // supplierNo: "",
        companyNo: "",
        good_code: "",
        good_name: "",
        outCode: "",
        status: "",
        company_name: "", //申请人部门
        page: 1, // 页码
        size: 15, // 每页显示条数
      };
      // 表格 - 分页
      this.pageInfo = {
        size: 15,
        curr: 1,
        total: 0,
      };
      await this.searchList();
    },
    async page_size_change(e) {
      this.parmValue.size = e;
      this.pageInfo.size = e;
      this.parmValue.page = 1;
      this.pageInfo.curr = 1;
      await this.searchList();
    },
    async page_curr_change(e) {
      this.parmValue.page = e;
      this.pageInfo.curr = e;
      await this.searchList();
    },
    async openAllModal() {
      const { good_num } = this.sitem;
      this.returnAllId = this.orderCode;
      this.returnAllSitem = {
        orderCode: this.orderCode,
        remark: "", //退货备注
        errorCode: "", //退货原因
        thnum: good_num + "",
        returnT: good_num + "",
      };
      this.returnAllShowModel = true;

      // await this.$confirm("确定要全部退货？", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning",
      // })
      //   .then(async () => {
      //     console.log("1111111111");
      //   })
      //   .catch(() => {
      //     console.log("取消");
      //   });
      //
    },
  },
};
</script>
<style lang="scss" scoped></style>
