<template>
  <div class="app-container">
    <el-row>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="订单号" prop="tid">
          <el-input
            v-model="queryParams.tid"
            placeholder="请输入订单号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="店铺" prop="shopId">
          <el-select v-model="queryParams.shopId" placeholder="请选择店铺" clearable @change="handleQuery">
            <el-option
              v-for="item in shopList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-select v-model="printParams.printer" placeholder="请选择打印机" clearable>
            <el-option
              v-for="item in printerList"
              :key="item.name"
              :label="item.name"
              :value="item.name">
            </el-option>
          </el-select>

        </el-form-item>
      </el-form>

    </el-row>


    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          :disabled="single"
          icon="el-icon-download"
          size="mini"
          @click="handleShip"
        >手动发货</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type=""
          plain
          :disabled="single"
          icon="el-icon-download"
          size="mini"
          @click="allocateShipmentToSupplier"
        >分配给供应商发货</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-time"
          size="mini"
          :disabled="multiple"
          @click="handleGetEwaybillCode"
        >电子面单取号&发货</el-button>
      </el-col>

      <el-col :span="1.5">

        <el-button
          type="success"
          plain
          :disabled="multiple"
          icon="el-icon-printer"
          size="mini"
          @click="handlePrintEwaybill"
        >电子面单打印</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-d-arrow-right"
          size="mini"
          :disabled="multiple"
          @click="handleShipSend"
        >电子面单发货</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
       <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="ID" align="center" prop="id" />-->
      <el-table-column label="订单号" align="left" prop="tid" width="180">
        <template slot-scope="scope">
          <p>{{scope.row.tid}}</p>
          <el-tag  effect="plain">{{shopList.find(x=>x.id === scope.row.shopId).name}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="商品" width="550">
        <template slot-scope="scope">
          <el-table :data="scope.row.items" :show-header="false">
            <el-table-column label="商品" align="center" prop="title" />
            <el-table-column label="规格" align="center" prop="skuPropertiesName" />
            <el-table-column label="数量" align="center" prop="num" width="60">
              <template slot-scope="scope">
                <el-tag size="small">x {{scope.row.num}}</el-tag>
              </template>
            </el-table-column>
          </el-table>
<!--          <el-row v-for="item in scope.row.items" :key="item.id" :gutter="20">-->

<!--            <div style="float: left;display: flex;align-items: center;" >-->

<!--              <div style="margin-left:10px">-->
<!--                <p>{{item.title}}</p>-->
<!--                <p>{{item.skuPropertiesName}}&nbsp;-->
<!--                  <el-tag size="small">x {{item.num}}</el-tag>-->
<!--                </p>-->

<!--              </div>-->
<!--            </div>-->
<!--          </el-row>-->
        </template>
      </el-table-column>
      <el-table-column label="下单时间" align="center" prop="orderCreateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.created) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="buyerMessage" >
        <template slot-scope="scope">
          <span v-if="scope.row.buyerMessage">买家留言:{{ scope.row.buyerMessage }}</span>
          <span v-if="scope.row.sellerMemo">卖家备注:{{ scope.row.sellerMemo }}</span>
        </template>
      </el-table-column>
<!--      <el-table-column label="买家留言" align="center" prop="buyerMessage" />-->
<!--      <el-table-column label="卖家备注" align="center" prop="sellerMemo" />-->

<!--      <el-table-column label="店铺" align="center" prop="categoryId" >-->
<!--        <template slot-scope="scope">-->
<!--          <el-tag size="small">{{categoryList.find(x=>x.id === scope.row.categoryId).name}}</el-tag>-->
<!--        </template>-->
<!--      </el-table-column>-->

      <el-table-column label="收件信息" align="left" prop="receiverState" >
        <template slot-scope="scope">
          <div>
            {{scope.row.receiverName}}&nbsp;{{scope.row.receiverMobile}}
          </div>
          <div>
            {{scope.row.receiverState}} &nbsp;{{scope.row.receiverCity}}&nbsp;{{scope.row.receiverDistrict}}&nbsp;{{scope.row.receiverTown}}
          </div>
          <div>
            {{scope.row.receiverAddress}}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="面单号" align="center" prop="erpSendCode" />
      <el-table-column label="状态" align="center" prop="erpSendStatus" >
        <template slot-scope="scope">
          <el-tag size="small" v-if="scope.row.erpSendStatus==0">未取号</el-tag>
          <el-tag size="small" v-if="scope.row.erpSendStatus==1">已取号</el-tag>
          <el-tag size="small" v-if="scope.row.erpSendStatus==2">已打印</el-tag>
          <el-tag size="small" v-if="scope.row.erpSendStatus==3">已发货</el-tag>
          <el-tag size="small" v-if="scope.row.erpSendStatus==10">手动发货</el-tag>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 取号 -->
    <el-dialog title="取号" :visible.sync="getCodeOpen" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="电子面单账户" prop="accountId">
            <el-select v-model="form.accountId" placeholder="请选择电子面单账户" clearable>
              <el-option
                v-for="item in deliverList"
                :key="item.id"
                :label="item.cpCode"
                :value="item.id">
                <span style="float: left">{{ item.cpCode }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px" >{{item.branchName}}:{{item.quantity}}</span>
              </el-option>
            </el-select>
          <el-button type="success" plain @click="updateWaybillAccount" >更新电子面单账户信息</el-button>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="getCodeOpenForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 打包发货对话框 -->
    <el-dialog title="打包发货" :visible.sync="shipOpen" width="1100px" append-to-body>

      <el-form ref="form" :model="form" :rules="rules" label-width="80px" >
        <el-descriptions title="订单信息">
          <el-descriptions-item label="ID">{{form.id}}</el-descriptions-item>
          <el-descriptions-item label="订单号">{{form.tid}}</el-descriptions-item>

          <el-descriptions-item label="店铺">
            {{ shopList.find(x=>x.id == form.shopId)?shopList.find(x=>x.id == form.shopId).name:'' }}
            <el-tag size="small" v-if="form.shopType === 5">微信小店</el-tag>

          </el-descriptions-item>
          <el-descriptions-item label="买家留言">
            {{form.buyerMemo}}
          </el-descriptions-item>
          <el-descriptions-item label="备注">
            {{form.remark}}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ parseTime(form.createTime) }}
          </el-descriptions-item>

          <el-descriptions-item label="订单状态">
            <el-tag v-if="form.orderStatus === 1" style="margin-bottom: 6px;">待发货</el-tag>
            <el-tag v-if="form.orderStatus === 2" style="margin-bottom: 6px;">已发货</el-tag>
            <el-tag v-if="form.orderStatus === 3" style="margin-bottom: 6px;">已签收</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="退款状态">
            <el-tag v-if="form.refundStatus === 1">无售后或售后关闭</el-tag>
            <el-tag v-if="form.refundStatus === 2">售后处理中</el-tag>
            <el-tag v-if="form.refundStatus === 3">退款中</el-tag>
            <el-tag v-if="form.refundStatus === 4">退款成功</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="">
            <!--            <el-tag v-if="form.shipType === 1"  type="danger">供应商代发</el-tag>-->
            <!--            <el-tag v-if="form.shipType === 0" type="danger">仓库发货</el-tag>-->
          </el-descriptions-item>
          <el-descriptions-item label="收件人姓名">{{form.receiverName}}</el-descriptions-item>
          <el-descriptions-item label="收件人手机号">{{form.receiverMobile}}</el-descriptions-item>
          <el-descriptions-item label="省市区">{{form.province}}{{form.city}}{{form.town}}</el-descriptions-item>
          <el-descriptions-item label="详细地址">{{form.address}}</el-descriptions-item>



        </el-descriptions>

        <el-divider content-position="center">商品明细</el-divider>
        <el-table :data="form.items"  style="margin-bottom: 10px;">
          <!-- <el-table-column type="selection" width="50" align="center" /> -->
          <el-table-column label="序号" align="center" type="index" width="50"/>

          <el-table-column label="商品图片" prop="goodsImg" width="80">
            <template slot-scope="scope">
              <el-image style="width: 70px; height: 70px" :src="scope.row.picPath"></el-image>
            </template>
          </el-table-column>
          <el-table-column label="商品标题" prop="title" ></el-table-column>
          <el-table-column label="规格" prop="skuPropertiesName" width="350"></el-table-column>
          <el-table-column label="sku编码" prop="outerSkuId"></el-table-column>
          <!--          <el-table-column label="单价" prop="goodsPrice"></el-table-column>-->
          <el-table-column label="数量" prop="num"></el-table-column>
          <!-- <el-table-column label="商品金额" prop="itemAmount"></el-table-column> -->
        </el-table>
        <el-form-item label="包裹尺寸" prop="height">
          <el-input type="number" v-model.number="form.length" placeholder="长mm" style="width:90px" /> x
          <el-input type="number"  v-model.number="form.width" placeholder="宽mm" style="width:90px" /> x
          <el-input type="number" v-model.number="form.height" placeholder="高mm" style="width:90px" />
        </el-form-item>
        <el-form-item label="包裹重量" prop="weight">
          <el-input type="number" v-model.number="form.weight" placeholder="请输入包裹重量（单位g）" style="width:300px" />
        </el-form-item>
        <el-row>
          <el-col>
            <el-form-item label="物流公司" prop="shippingCompany">
              <!--              <el-input v-model="form.shippingCompany" placeholder="请输入物流公司" style="width:300px" />-->
              <el-select v-model="form.shippingCompany" filterable r placeholder="选择快递公司" style="width:300px">
                <el-option v-for="item in logisticsList" :key="item.id" :label="item.name" :value="item.id">
                  <span style="float: left">{{ item.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px" >{{item.number}}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="物流单号" prop="shippingNumber">
              <el-input v-model="form.shippingNumber" placeholder="请输入物流单号" style="width:300px" />
            </el-form-item>
            <el-form-item label="物流费用" prop="shippingCost">
              <el-input v-model="form.shippingCost" placeholder="请输入物流费用" style="width:300px" />
            </el-form-item>
            <el-form-item label="发货人" prop="shippingMan">
              <el-input v-model="form.shippingMan" placeholder="请输入发货人" style="width:300px" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitShipForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 分配给供应商发货对话框 -->
    <el-dialog title="分配给供应商发货" :visible.sync="allocateShipmentOpen" width="1100px" append-to-body>

      <el-form ref="form" :model="form" :rules="rules" label-width="80px" >
        <el-descriptions title="订单信息">
          <el-descriptions-item label="订单号">{{form.tid}}</el-descriptions-item>

          <el-descriptions-item label="买家留言">
            {{form.buyerMemo}}
          </el-descriptions-item>
          <el-descriptions-item label="备注">
            {{form.remark}}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ parseTime(form.createTime) }}
          </el-descriptions-item>


          <el-descriptions-item label="收件人姓名">{{form.receiverName}}</el-descriptions-item>
          <el-descriptions-item label="收件人手机号">{{form.receiverMobile}}</el-descriptions-item>
          <el-descriptions-item label="省市区">{{form.province}}{{form.city}}{{form.town}}</el-descriptions-item>
          <el-descriptions-item label="详细地址">{{form.address}}</el-descriptions-item>



        </el-descriptions>

        <el-divider content-position="center">商品明细</el-divider>
        <el-table :data="form.items"  style="margin-bottom: 10px;">
          <!-- <el-table-column type="selection" width="50" align="center" /> -->
          <el-table-column label="序号" align="center" type="index" width="50"/>

          <el-table-column label="商品图片" prop="goodsImg" width="80">
            <template slot-scope="scope">
              <el-image style="width: 70px; height: 70px" :src="scope.row.picPath"></el-image>
            </template>
          </el-table-column>
          <el-table-column label="商品标题" prop="title" ></el-table-column>
          <el-table-column label="规格" prop="skuPropertiesName" width="350"></el-table-column>
          <el-table-column label="sku编码" prop="outerSkuId"></el-table-column>
          <!--          <el-table-column label="单价" prop="goodsPrice"></el-table-column>-->
          <el-table-column label="数量" prop="num"></el-table-column>
          <!-- <el-table-column label="商品金额" prop="itemAmount"></el-table-column> -->
        </el-table>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAllocateShipmentForm">分配给供应商发货</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

import {listLogisticsStatus, listShop} from "@/api/shop/shop";
import {getOrder, listOrder,allocateShipmentOrder,manualShipmentOrder} from "@/api/tao/order";
import {
  getWaybillAccountList,
  pullWaybillAccount,
  getWaybillCode,
  getWaybillPrintData,
  pushWaybillPrintSuccess, pushShipSend
} from "@/api/tao/ewaybill";

export default {
  name: "printTao",
  data() {
    return {
      // 遮罩层
      loading: true,
      shipOpen: false,
      allocateShipmentOpen: false,
      // 选中数组
      ids: [],
      shopList: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 取号弹出
      getCodeOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        status: 'WAIT_SELLER_SEND_GOODS',
        erpSendStatus:-1,//-1代表未发货的
        shopId: null
      },
      // 打印参数
      printParams: {
        deliver: null,
        printer: null
      },
      // 表单参数
      form: {},
      orderList: [],
      logisticsList: [],
      printerList: [],
      deliverList: [],
      // 表单校验
      rules: {
        accountId: [{ required: true, message: '请选择电子面单账户' }],
        height: [{ required: true, message: '不能为空' }],
        weight: [{ required: true, message: '不能为空' }],
        shippingNumber: [{ required: true, message: '不能为空' }],
        shippingCompany: [{ required: true, message: '不能为空' }],
        shippingCost: [{ required: true, message: '不能为空' }],
      }
    };
  },
  created() {
    this.openWs()
    listShop({type: 100}).then(response => {
      this.shopList = response.rows;
      if (this.shopList && this.shopList.length > 0) {
        this.queryParams.shopId = this.shopList[0].id
      }
      this.getList();
    });
  },
  methods: {
    /** 查询商品管理列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.getCodeOpen = false;
      this.shipOpen = false;
      this.allocateShipmentOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        erpSkuId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    openWs() {
      this.$modal.msgError("开源版本未实现电子面单相关功能！请自行对接发货");
    },
    // 取号弹窗
    handleGetEwaybillCode() {
      const ids = this.ids;
      if (ids) {
        getWaybillAccountList({shopId: this.queryParams.shopId}).then(response => {
          this.deliverList = response.data;
          this.getCodeOpen = true
        });
      } else {
        this.$modal.msgError("请选择订单")
      }
    },
    // 更新电子面单信息
    updateWaybillAccount() {
      pullWaybillAccount({shopId: this.queryParams.shopId}).then(response => {
        this.deliverList = response.data;
      });
    },
    /** 取号提交按钮 */
    getCodeOpenForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const ids = this.ids;
          console.log('=========3333========', ids)
          if (ids) {
            console.log('===请求参数=====', {shopId: this.queryParams.shopId, ids: ids, accountId: this.form.accountId})
            getWaybillCode({
              shopId: this.queryParams.shopId,
              ids: ids,
              accountId: this.form.accountId
            }).then(response => {
              this.$modal.msgSuccess("取号成功")
              this.getList()
              this.getCodeOpen = false
            });
          } else {
            this.$modal.msgError("请选择订单")
          }
        }
      });
    },
    handlePrintEwaybill() {
      // if (!this.ws) {
      //   this.$modal.msgError('打印组件连接失败！请安装并启动微信视频号小单打印组件！');
      //   this.openWs()
      // }
      // if(!this.printParams.deliver){
      //   this.$modal.msgError('请选择快递公司！');
      //   return
      // }
      if (!this.printParams.printer) {
        this.$modal.msgError('请选择打印机！');
        return
      }
      const ids = this.ids;
      getWaybillPrintData({shopId: this.queryParams.shopId, ids: ids}).then(response => {
        console.log("======打印======", response.data)
        if (response.data) {
          console.log('===开源版本暂不支持====')
        }
      });


    },
    handleShipSend(){
      // this.$modal.msgError("开源版本未实现平台发货！请自行对接发货");
      pushShipSend({shopId: this.queryParams.shopId, ids: this.ids}).then(response => {
        this.$modal.msgSuccess("发货成功！");
        this.getList()
      })
    },
    // 分配给供应商发货
    allocateShipmentToSupplier(row){
      this.reset();
      const id = row.id || this.ids
      console.log('======',id)
      getOrder(id).then(response => {
        this.form = response.data;
        this.allocateShipmentOpen = true;
        // this.detailTitle = "订单详情";
      });
    },
    // 手动发货按钮
    handleShip(row){
      this.reset();
      const id = row.id || this.ids
      console.log('======',id)
      getOrder(id).then(response => {
        this.form = response.data;
        this.form.length=0
        this.form.width=0
        this.form.height=0
        this.form.weight=0.0
        this.form.shippingCost=0.0
        listLogisticsStatus({}).then(resp=>{
          this.logisticsList = resp.rows
        })
        this.shipOpen = true;
        // this.detailTitle = "订单详情";
      });
    },
    // 手动发货表单
    submitShipForm(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          manualShipmentOrder(this.form).then(resp =>{
            this.$modal.msgSuccess("手动发货成功");
            this.shipOpen = false
            this.getList()
          })
        }
      })
    },
    // 分配给供应商发货
    submitAllocateShipmentForm(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          allocateShipmentOrder(this.form).then(resp =>{
            if(resp.code==200){
              this.$modal.msgSuccess("分配发货成功");
              this.allocateShipmentOpen = false
              this.getList()
            }else{
              this.$modal.msgError(resp.msg);
            }

          })
        }
      })
    }
  }
};
</script>
