<template>
  <div>
    <div>
      <el-tabs v-model="params.selectType" type="card" @tab-click="handleClick">
        <el-tab-pane label="未发货" name="to_be_send"></el-tab-pane>
        <el-tab-pane label="已发货" name="sending"></el-tab-pane>
      </el-tabs>
    </div>
    <div class="search">
      <el-form ref="advancedForm" :model="advancedForm" label-width="160px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="订单日期">
              <el-date-picker v-model="advancedForm.goodsExchange_time_range" type="daterange" align="center"
                :editable="false" unlink-panels :clearable="true" :default-time="['00:00:00', '23:59:59']"
                range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" value-format="timestamp"
                :picker-options="{
                  disabledDate(time) {
                    return (
                      time.getTime() - 1 >=
                      new Date(
                        new Date().getFullYear(),
                        new Date().getMonth(),
                        new Date().getDate()
                      ).getTime() +
                      86400000 -
                      1
                    );
                  },
                  shortcuts: MixinPickerShortcuts,
                }">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="仓库">
              <el-select v-model="advancedForm.warehouse_id" clearable>
                <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="订单编号">
              <el-input v-model="advancedForm.sn" clearable placeholder="请输入订单编号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-button @click="advancedSearchEvent"> 搜索 </el-button>
    </div>
    <en-table-layout :tableData="tableData.records" :loading="loading" @selection-change="handleSelectionChange"
      :row-style="changRed">
      <div slot="toolbar" class="inner-toolbar">
        <div class="toolbar-btns">
          <span v-if="params.selectType == 'sending'">已发货:{{ tableData.total }}</span>
          <!-- <el-button size="mini" @click="addWarehouse">新增</el-button>
          <el-button size="mini">发货</el-button>
          <el-button size="mini" v-if="checkPermission(['warehouseOut:del'])" @click="handleDeleteWarehouseOut()" type="danger"
            :disabled="multipleSelection.length === 0">删除</el-button> -->
        </div>
      </div>
      <template slot="table-columns">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="" label="订单编号">
          <template slot-scope="scope">
            {{ scope.row.sn }}
          </template>
        </el-table-column>
        <el-table-column prop="sn" label="出库单编号" v-if="params.selectType == 'sending'">
          <template slot-scope="scope">
            {{ scope.row.sn }}
          </template>
        </el-table-column>
        <el-table-column label="客户">
          <template slot-scope="scope">
            {{ memberType(scope.row.order_vo.member_id) }}
          </template>
        </el-table-column>
        <el-table-column prop="order_time" label="下单时间">
          <template slot-scope="scope">{{
            scope.row.create_time | unixToDate
            }}</template>
        </el-table-column>
        <el-table-column prop="warehouse_name" label="仓库名称">
          <template slot-scope="scope">
            {{ warehouseName(scope.row.warehouse_id) }}
          </template>
        </el-table-column>
        <el-table-column prop="" label="配送方式">
          <template slot-scope="scope">{{
            deliveryType(scope.row.order_vo.send_type)
            }}</template>
        </el-table-column>
        <!--        <el-table-column prop="distribution_name" label="销售经理" />-->
        <el-table-column prop="" label="付款方式">
          <template slot-scope="scope">
            {{ payType(scope.row.order_vo.pay_type) }}
          </template>
        </el-table-column>
        <!--        <el-table-column prop="audit_by" label="审核人" />-->
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">{{
            typeName(scope.row.status)
            }}</template>
        </el-table-column>
        <!-- <el-table-column prop="status" label="发货状态">
          <template slot-scope="scope">{{ statusFilter(scope.row.status) }}</template>
        </el-table-column> -->
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button size="mini" v-if="scope.row.status !== 'TO_BE_SEND'" type="success"
              @click="handleAuditDialog(scope.row)">查看</el-button>
            <!---->
            <!--  <el-button size="mini" v-if="scope.row.allowable.ship && checkPermission(['warehouseOut:send'])" type="success"
              @click="handleSendWarehouseOut(scope.row)">发货</el-button> -->
            <el-button v-if="scope.row.status == 'TO_BE_SEND' && checkPermission(['orderOutboundAdd'])" size="mini"
              @click="addWarehouse(scope.row)">发货</el-button>
            <!-- <el-button type="primary" size="mini" @click="handlePrintWarehouseOutDialog(scope.row)">删除</el-button> -->
          </template>
        </el-table-column>
      </template>

      <el-pagination v-if="tableData" slot="pagination" @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange" :current-page="tableData.pages" :page-sizes="[10, 20, 50, 100]"
        :page-size="tableData.size" layout="total, sizes, prev, pager, next, jumper" :total="tableData.total">
      </el-pagination>
    </en-table-layout>

    <el-dialog title="出库单表" :visible.sync="dialogVisible" width="940px" center>
      <el-button size="mini" type="primary" @click="handlePrintWarehouseOut" class="print">打印</el-button>
      <div id="deliverySheet" style="width: 900px">
        <div class="tips-t">
          <div>
            仓库名称编码:<span v-if="warehouseOutForm.dept_name">{{ warehouseOutForm.dept_name }}部门</span><span
              v-if="warehouseOutForm.warehouse_name">{{ warehouseOutForm.warehouse_name }}仓库</span>
          </div>
          <div>日期:{{ warehouseOutForm.out_time | unixToDateStr }}</div>
          <div>编号:{{ warehouseOutForm.sn }}</div>
        </div>
        <div class="tips-t" style="margin: 0 20px">
          <div>用户电话:{{ warehouseOutForm.member_mobile }}</div>
          <div>用户姓名:{{ warehouseOutForm.member_real_name }}</div>
          <div>
            <!--            用户收货地址:{{ warehouseOutForm.ship_addr }}-->
          </div>
        </div>
        <el-table :data="warehouseOutForm.item_list" border :cell-style="{ textAlign: 'center' }"
          :header-cell-style="{ textAlign: 'center', background: '#f4f4f4' }" style="width: 100%; margin-top: 20px">
          <el-table-column label="产品编码">
            <template slot-scope="scope">
              {{ scope.row.product_sn }}
            </template>
          </el-table-column>
          <el-table-column label="产品名称">
            <template slot-scope="scope">
              {{ scope.row.product_name }}
            </template>
          </el-table-column>
          <el-table-column label="规格型号">
            <template slot-scope="scope">
              {{ scope.row.product_specification }}
            </template>
          </el-table-column>
          <el-table-column label="数量">
            <template slot-scope="scope">
              {{ scope.row.out_num }}
            </template>
          </el-table-column>
        </el-table>
        <div class="tips-t">
          <div>提货人:{{ warehouseOutForm.consignee }}</div>
          <div>
            客户订单号:{{
              warehouseOutForm.order_sn_list
                ? formatFilter(warehouseOutForm.order_sn_list)
                : ""
            }}
          </div>
          <div>制单人:{{ warehouseOutForm.create_by }}</div>
        </div>
      </div>
    </el-dialog>
    <el-dialog title="订单发货" :visible.sync="dialogSendVisible" width="450px">
      <el-form :model="warehouseOutForms" ref="warehouseOutForms" label-width="120px">
        <el-form-item label="出库单号:" prop="name">
          {{ warehouseOutForms.sn }}
        </el-form-item>
        <el-form-item label="订单编号:" prop="sn">
          <span v-if="warehouseOutForms.order_sn_list">{{
            formatFilter(warehouseOutForms.order_sn_list)
            }}</span>
        </el-form-item>
        <el-form-item label="配送方式:" prop="category_id">
          <el-radio v-model="warehouseOutForms.delivery_type" :label="'express'" :disabled="true">物流配送</el-radio>
          <el-radio v-model="warehouseOutForms.delivery_type" :label="'self_pick'" :disabled="true">自提</el-radio>
        </el-form-item>
        <span v-if="warehouseOutForms.delivery_type === 'self_pick'">
          <el-form-item label="自提点:" prop="store_id">
            {{ warehouseOutForms.store_name }}
          </el-form-item>
          <el-form-item label="物流费用:" prop="freight_price">
            <el-input v-model="warehouseOutForms.freight_price" type="number"
              oninput="value=parseInt(value.replace(/[^\d]/g,''))" :minlength="1" :maxlength="20" clearable
              placeholder="请输入物流费用"></el-input>
          </el-form-item>
          <el-form-item label="提货人:" prop="consignee">
            <el-input v-model="warehouseOutForms.consignee" :minlength="1" :maxlength="20" clearable
              placeholder="请输入提货人"></el-input>
          </el-form-item>
        </span>
        <span v-else>
          <el-form-item label="物流公司:" prop="logistics_company_id">
            <el-select v-model="warehouseOutForms.logistics_company_id">
              <el-option v-for="item in expressCompanyList" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="物流单号:" prop="tracking_number">
            <el-input v-model="warehouseOutForms.tracking_number" :minlength="1" :maxlength="20" clearable
              placeholder="请输入物流单号"></el-input>
          </el-form-item>
          <el-form-item label="物流费用:" prop="freight_price">
            <el-input v-model="warehouseOutForms.freight_price" type="number"
              oninput="value=parseInt(value.replace(/[^\d]/g,''))" :minlength="1" :maxlength="20" clearable
              placeholder="请输入物流费用"></el-input>
          </el-form-item>
          <el-form-item label="提货人:" prop="consignee">
            <el-input v-model="warehouseOutForms.consignee" :minlength="1" :maxlength="20" clearable
              placeholder="请输入提货人"></el-input>
          </el-form-item>
        </span>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogSendVisible = false">取 消</el-button>
        <el-button type="primary" @click="warehouseOutShip">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="审核" :visible.sync="auditVisible" width="500px" center>
      <span>请选择审核状态：</span>
      <el-radio v-model="auditStatus" label="AUDIT_PASS">通过</el-radio>
      <el-radio v-model="auditStatus" label="AUDIT_REJECT">驳回</el-radio>
      <div class="btn-box">
        <el-button type="" @click="auditVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAuditWarehouseOut">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as API_Order from "@/api/order";
import Print from "print-js";
import * as API_Setting from "@/api/setting";
import { Foundation } from "~/ui-utils";
import * as API_BasicSetting from "@/api/basicSetting";
import * as API_CollectingAccount from "@/api/collectingAccount";
export default {
  name: "warehouseOut",
  data() {
    return {
      warehouseList: [],
      deptList: [],
      expressCompanyList: [],
      // 列表loading状态
      loading: false,
      // 列表参数
      params: {
        page_no: 1,
        page_size: 10,
        selectType: "to_be_send",
      },
      // 高级搜索数据
      advancedForm: {},
      // 列表数据
      tableData: "",
      dialogVisible: false,
      dialogSendVisible: false,
      // 当前已选择的行
      multipleSelection: [],
      orderType: [],
      warehouseOutForm: {},
      warehouseOutForms: {},
      // 审核弹窗显隐
      auditVisible: false,
      // 当前操作审核ID
      auditId: "",
      // 审核状态
      auditStatus: "AUDIT_PASS",
      activeShipped: "unShipped",
      deliveryTypeList: [],
      collectingAccountList: [], // 支付方式列表
      customerList: [],
    };
  },
  mounted() {
    this.GET_WarehouseOutList();
    this.GET_DeptList();
    this.GET_ExpressCompanyList();
    this.GET_WarehouseList();
    this.GET_CollectingAccountList();
  },
  watch: {
    $route: function ({ query }) {
      this.params.page_no = 1;
      this.GET_WarehouseOutList();
    },
  },
  methods: {
    /** 获取支付方式列表 */
    GET_CollectingAccountList() {
      API_CollectingAccount.getList({
        page_no: 1,
        page_size: -1,
        enable_flag: true,
      }).then((response) => {
        this.collectingAccountList = response.data;
      });
    },
    changRed({ row }) {
      if (row.subtract_stock) { // 变颜色的条件
        return {
          color: "red"  // 这个return的就是样式 可以是color 也可以是backgroundColor
        }
      }
    },
    memberType(val) {
      let name = "";
      this.customerList.map((el) => {
        if (el.id == val) {
          return (name = el.name);
        }
      });
      return name;
    },
    //获取付款方式
    payType(val) {
      let name = "";
      this.collectingAccountList.map((el) => {
        if (el.id == val) {
          return (name = el.name);
        }
      });
      return name;
    },
    //配送方式查看
    deliveryType(val) {
      let name = "";
      this.deliveryTypeList.map((el) => {
        if (el.value == val) {
          return (name = el.label);
        }
      });
      return name;
    },
    //获取仓库名称
    warehouseName(val) {
      /*   let wareName=''
        let name = [];
        this.warehouseList.map((el) => {
            if (el.id == val) {
              return name.push(el.name);
            }
        });
        name.map(e=>{
          wareName=e
        })
       return wareName */
      let wareName = this.warehouseList.find(el => el.id === val).name || '';
      return wareName;
    },
    //获取订单状态大小写转换.toUpperCase()
    typeName(val) {
      let name = "";
      this.orderType.map((el) => {
        if (el.value == val) {
          return (name = el.label);
        }
      });
      return name;
    },
    /* 切换发货列表 */
    handleClick(tab, event) {
      if (tab.name == "to_be_send") {
        this.params.selectType = tab.name;
        this.GET_WarehouseOutList();
      } else {
        this.params.selectType = tab.name;
        this.GET_WarehouseOutList();
      }
    },
    addWarehouse(row) {
      this.$router.push({
        name: "orderOutboundAdd",
        params: { id: row.id, send_type: row.order_vo.send_type },
      });
      // this.$router.params{ name: 'orderOutboundDetail', params: { id: scope.row.id } }
    },
    /** 查看 */
    handleAuditDialog(row) {
      this.$router.push({
        name: "orderOutboundAdd",
        params: { id: row.id, type: "check", send_type: row.order_vo.send_type },
      });
    },
    /** 审核提交 */
    handleAuditWarehouseOut() {
      API_Order.handleAuditWarehouseOut(this.auditId, {
        status: this.auditStatus,
      }).then((response) => {
        this.$message.success("提交成功！");
        this.auditVisible = false;
        this.GET_WarehouseOutList();
      });
    },
    GET_ExpressCompanyList() {
      API_Order.getExpressCompanyList({ page_no: 1, page_size: 9999 }).then(
        (response) => {
          this.expressCompanyList = response.data;
        }
      );
    },
    warehouseOutShip() {
      API_Order.warehouseOutShip(this.warehouseOutForms).then((response) => {
        this.$message.success("发货成功！");
        this.GET_WarehouseOutList();
        this.dialogSendVisible = false;
      });
    },
    formatFilter(val) {
      return val.join(",");
    },
    /** 出库单状态 */
    statusFilter(val) {
      switch (val) {
        case "WAIT_SHIP":
          return "待发货";
        case "WAIT_AUDIT":
          return "待发货";
        case "SHIP":
          return "已发货";
        default:
          return "";
      }
    },
    /** 获取仓库 */
    GET_WarehouseList() {
      API_BasicSetting.getWarehouseListAll().then((response) => {
        this.warehouseList = response;
      });
      API_BasicSetting.customer(this.params).then((response) => {
        this.customerList = response.data;
      });
      API_Setting.getPage({ dictType: "order_send_type" }).then((res) => {
        this.deliveryTypeList = res.data;
      });
    },
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getDeptList().then((response) => {
        this.deptList = Foundation.buildTree(response, "0");
      });
      API_Setting.getPage({ dictType: "Sale_order_send_status" }).then((res) => {
        this.orderType = res.data;
      });
    },
    /** 打印对账详情 */
    handlePrintWarehouseOut() {
      Print({
        printable: "deliverySheet",
        type: "html",
        targetStyles: ["*"],
        ignoreElements: ["no-logs", "goods-image", "no-btn"],
      });
    },
    handleDeleteWarehouseOut() {
      this.$confirm("确定要删除这些出库单吗？", "提示", { type: "warning" })
        .then(() => {
          const ids = this.multipleSelection.map((item) => item.id);
          API_Order.deleteWarehouseOut(ids).then(() => {
            this.$message.success("删除成功！");
            this.GET_WarehouseOutList();
          });
        })
        .catch(() => { });
    },
    /** 多选改变 */
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    /** 分页大小发生改变 */
    handlePageSizeChange(size) {
      this.params.page_size = size;
      this.GET_WarehouseOutList();
    },

    /** 分页页数发生改变 */
    handlePageCurrentChange(page) {
      this.params.page_no = page;
      this.GET_WarehouseOutList();
    },

    /** 发货 */
    handleSendWarehouseOut(row) {
      this.warehouseOutForms = row;
      // this.dialogSendVisible = trueorderOutboundDetail
      this.$router.push({
        name: "orderOutboundAdd",
        params: { id: row.id },
      });
    },
    /** 打印出库单 */
    handlePrintWarehouseOutDialog(row) {
      this.GET_WarehouseOutDetail(row.id);
    },
    /** 获取出库单详情页面数据 */
    GET_WarehouseOutDetail(id) {
      API_Order.getWarehouseOutInfo(id).then((response) => {
        this.warehouseOutForm = response;
        if (response.product_list && response.product_list.length) {
          var str = "";
          response.product_list.forEach(function (i) {
            str += i.product_name + "、";
          });
        }
        this.warehouseOutForm.illustrate = str;
        this.dialogVisible = true;
      });
    },
    /** 搜索事件触发 */
    searchEvent(data) {
      this.params = {
        ...this.params,
        sn: data,
      };
      Object.keys(this.advancedForm).forEach((key) => delete this.params[key]);
      this.params.page_no = 1;
      this.GET_WarehouseOutList();
    },
    /** 高级搜索事件触发 */
    advancedSearchEvent() {
      this.params = {
        ...this.params,
        ...this.advancedForm,
      };
      delete this.params.start_time;
      delete this.params.end_time;
      if (this.advancedForm.warehouseOut_time_range) {
        this.params.start_time = parseInt(
          Number(this.advancedForm.warehouseOut_time_range[0]) / 1000
        );
        this.params.end_time = parseInt(
          Number(this.advancedForm.warehouseOut_time_range[1]) / 1000
        );
      }
      delete this.params.warehouseOut_time_range;
      this.params.page_no = 1;
      this.GET_WarehouseOutList();
    },
    /** 获取出库单列表 */
    GET_WarehouseOutList() {
      this.loading = true;
      API_Order.getSaleOrderOutList(this.params)
        .then((response) => {
          this.loading = false;
          this.tableData = response;
        })
        .catch(() => {
          this.loading = false;
        });

    },
  },
};
</script>

<style type="text/scss" lang="scss" scoped>
.search {
  display: flex;
  align-items: center;
  background: #fff;
  overflow: hidden;
  padding: 30px 10px 10px 10px;

  /deep/ .el-form-item {
    .el-form-item__content {
      .el-input {
        width: 200px;
      }
    }
  }

  .el-button {
    margin-top: -19px;
    margin-left: 20px;
  }
}

.print {
  margin-left: 790px;
}

.btn-box {
  text-align: center;
  margin: 30px 0 10px;
}

.tips-t {
  display: flex;
  padding: 10px 0;

  div {
    flex: 1;
    text-align: center;
  }
}

.tips-f {
  padding: 20px 0;
}

.face-image {
  display: block;
  width: 50px;
  height: 50px;
  margin: 0 auto;
}

/deep/ .el-dialog__body {
  padding: 10px 20px;
}
</style>
