<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单号" prop="orderCode">
        <el-input
        style="width:220px"
          v-model="queryParams.orderCode"
          placeholder="请输入订单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
       <el-form-item label="运单号" prop="deliveryId">
        <el-input
        style="width:220px"
          v-model="queryParams.deliveryId"
          placeholder="请输入运单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="收件人" prop="realName">
            <el-input
            style="width:220px"
              v-model="queryParams.realName"
              placeholder="请输入收件人"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号" prop="userPhone">
            <el-input
            style="width:220px"
              v-model="queryParams.userPhone"
              placeholder="请输入收件人手机号"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
       <el-form-item label="订单类型" prop="orderType">
         <el-select style="width:220px"  v-model="queryParams.orderType" placeholder="请选择订单类型" clearable size="small" >
         <el-option
                v-for="item in orderTypeOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
        </el-select>
      </el-form-item>
      <el-form-item label="上传凭证" prop="isUpload">
         <el-select   v-model="queryParams.isUpload" placeholder="请选择" clearable size="small" >
          <el-option key="0"  label="未上传" value="0" />
             <el-option key="1"  label="已上传" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="物流状态" prop="deliveryStatus">
         <el-select style="width:220px" v-model="queryParams.deliveryStatus" placeholder="请选择物流状态" clearable size="small" >
         <el-option
                v-for="item in deliveryStatusOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
        </el-select>
      </el-form-item>
      <el-form-item label="结算状态" prop="deliveryPayStatus">
         <el-select style="width:220px" v-model="queryParams.deliveryPayStatus" placeholder="请选择物流结算状态" clearable size="small" >
         <el-option
                v-for="item in deliveryPayStatusOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
        </el-select>
      </el-form-item>
      <el-form-item label="下单时间" prop="createTimeRange">
        <el-date-picker
        style="width:220px"
          clearable size="small"
          v-model="createTimeRange"
          type="daterange"
          value-format="yyyy-MM-dd"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="支付时间" prop="payTimeRange">
        <el-date-picker
        style="width:220px"
          clearable size="small"
          v-model="payTimeRange"
          type="daterange"
          value-format="yyyy-MM-dd"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="回单时间" prop="deliveryImportTimeRange">
        <el-date-picker
        style="width:220px"
          clearable size="small"
          v-model="deliveryImportTimeRange"
          type="daterange"
          value-format="yyyy-MM-dd"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" 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>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="warning"
          icon="el-icon-download"
          size="mini"
            @click="handleExport"
          v-hasPermi="['store:storeOrder:export']"
        >导出订单</el-button>
      </el-col>
       <el-col :span="1.5">
        <el-button
            type="warning"
          icon="el-icon-download"
          size="mini"
            @click="handleExportItems"
          v-hasPermi="['store:storeOrder:exportItems']"
        >导出订单明细</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-tabs type="card" v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="全部订单" name="00"></el-tab-pane>
      <el-tab-pane label="待支付" name="0"></el-tab-pane>
      <el-tab-pane label="待发货" name="1"></el-tab-pane>
      <el-tab-pane label="待收货" name="2"></el-tab-pane>
      <el-tab-pane label="交易完成" name="3"></el-tab-pane>
      <el-tab-pane label="退款中" name="-1"></el-tab-pane>
      <el-tab-pane label="已退款" name="-2"></el-tab-pane>
      <el-tab-pane label="已取消" name="-3"></el-tab-pane>
    </el-tabs>
    <el-table height="500" border v-loading="loading" :data="storeOrderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单号" align="center" prop="orderCode" />
      <el-table-column label="所属公司" align="center" prop="companyName" />
      <el-table-column label="所属员工" align="center" prop="companyUserNickName" />
      <el-table-column label="用户昵称" align="center" prop="nickname" width="150px" >
          <template slot-scope="scope">
              <span>{{scope.row.nickname}}</span>
          </template>
      </el-table-column>
      <el-table-column label="收件人" align="center" prop="realName" width="150px" >
          <template slot-scope="scope">
              <span>{{scope.row.realName}} </span>
          </template>
      </el-table-column>
      <!-- <el-table-column label="商品" align="center" width="300px" >
          <template slot-scope="scope">
              <div  v-for="(item, index) in scope.row.items" class="items"  >
                <img class="pic" :src="JSON.parse(item.jsonInfo).image" />
                <div class="goods-content">
                  <div class="goods-title">{{ JSON.parse(item.jsonInfo).productName}}</div>
                  <div class="sku">{{ JSON.parse(item.jsonInfo).sku}}</div>
                  <div class="price">￥{{JSON.parse(item.jsonInfo).price}}×{{item.num}}</div>
                </div>
                
              </div>
          </template>
      </el-table-column> -->
      <el-table-column label="订单金额" align="center" prop="totalPrice" >
          <template slot-scope="scope">
              <span v-if="scope.row.totalPrice!=null">{{scope.row.totalPrice.toFixed(2)}}</span>
          </template>
      </el-table-column>
       <el-table-column label="应付金额" align="center" prop="payPrice" >
          <template slot-scope="scope">
              <span v-if="scope.row.payPrice!=null">{{scope.row.payPrice.toFixed(2)}}</span>
          </template>
      </el-table-column>
      <el-table-column label="下单时间" align="center" prop="createTime" />
      <!-- <el-table-column label="支付状态" align="center" prop="paid" /> -->
      <el-table-column label="支付时间" align="center" prop="payTime" width="180">
      </el-table-column>
      <el-table-column label="支付方式" align="center" prop="payType" >
          <template slot-scope="scope">
              <span prop="payType" v-for="(item, index) in payTypeOptions"    v-if="scope.row.payType==item.dictValue">{{item.dictLabel}}</span>
          </template>
      </el-table-column>
      <el-table-column label="订单类型" align="center" prop="orderType" >
          <template slot-scope="scope">
              <el-tag prop="status" v-for="(item, index) in orderTypeOptions"    v-if="scope.row.orderType==item.dictValue">{{item.dictLabel}}</el-tag>
          </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" >
          <template slot-scope="scope">
              <el-tag prop="status" v-for="(item, index) in statusOptions"    v-if="scope.row.status==item.dictValue">{{item.dictLabel}}</el-tag>
          </template>
      </el-table-column>
      <el-table-column label="物流状态" align="center" prop="deliveryStatus" >
          <template slot-scope="scope">
              <el-tag prop="status" v-for="(item, index) in deliveryStatusOptions"    v-if="scope.row.deliveryStatus==item.dictValue">{{item.dictLabel}}</el-tag>
          </template>
      </el-table-column>
      <el-table-column label="物流结算状态" align="center" prop="deliveryPayStatus" >
          <template slot-scope="scope">
              <el-tag prop="status" v-for="(item, index) in deliveryPayStatusOptions"    v-if="scope.row.deliveryPayStatus==item.dictValue">{{item.dictLabel}}</el-tag>
          </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="100px" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleDetails(scope.row)"
            v-hasPermi="['store:storeOrder:query']"
          >查看</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            @click="handleGenPayUrl(scope.row)"
            v-hasPermi="['store:storeOrder:genPayUrl']"
          >生成付款链接</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-drawer
     size="75%"
      :title="show.title" :visible.sync="show.open"
      >
      <product-order  ref="order" />
    </el-drawer>
  </div>
</template>

<script>
import {myListStoreOrder,exportStoreOrderItems, createUserOrder,listStoreOrder, getStoreOrder, delStoreOrder, addStoreOrder, updateStoreOrder, exportStoreOrder } from "@/api/store/storeOrder";
import { getUserList } from "@/api/users/user";
import { getAddressList } from "@/api/users/userAddress";

import productOrder from "../components/productOrder";
import productSelect from "../components/productSelect";
import addUser from "../components/addUser";
import addUserAddress from "../components/addUserAddress";
import config from "@/utils/config";
import QRCode from 'qrcodejs2'
export default {
  components: { productOrder,productSelect,addUser,addUserAddress },
  name: "StoreOrder",
  data() {
    return {
      deliveryPayStatusOptions:[],
      deliveryStatusOptions:[],
      dateRange: [],
      orderTypeOptions:[],
      payTypeOptions:[],
      payQr:{
        open:false,
        title:"付款二维码"
      },
      user:{
        open:false,
        title:"创建会员"
      },
      userAddress:{
        open:false,
        title:"创建收货地址"
      },
      tablekey:false,
      totalMoney:0.00,
      products:[],
      product:{
        open:false,
        title:"商品选择"
      },
      userStatusOptions:[],
      phone:null,
      address:[],
      addressloading: false,
      userloading: false,
      users:[],
      userStatusOptions:[],
      show:{
        open:false,
        title:"订单详情"
      },
      activeName:"00",
      statusOptions:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      storeOrderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      createTimeRange:[],
      payTimeRange:[],
      deliveryImportTimeRange:[],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderCode: null,
        extendOrderId: null,
        userId: null,
        realName: null,
        userPhone: null,
        userAddress: null,
        cartId: null,
        freightPrice: null,
        totalNum: null,
        totalPrice: null,
        totalPostage: null,
        payPrice: null,
        payPostage: null,
        deductionPrice: null,
        couponId: null,
        couponPrice: null,
        paid: null,
        payTime: null,
        payType: null,
        status: null,
        refundStatus: null,
        refundReasonWapImg: null,
        refundReasonWapExplain: null,
        refundReasonTime: null,
        refundReasonWap: null,
        refundReason: null,
        refundPrice: null,
        deliverySn: null,
        deliveryName: null,
        deliveryType: null,
        deliveryId: null,
        gainIntegral: null,
        useIntegral: null,
        payIntegral: null,
        backIntegral: null,
        mark: null,
        isDel: null,
        cost: null,
        verifyCode: null,
        storeId: null,
        shippingType: null,
        isChannel: null,
        isRemind: null,
        isSysDel: null
      },
      // 表单参数
      form: {
        addressId:null,
        userId:null,
        products:[],
      },
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "会员信息不能为空" }
        ],
        addressId: [
          { required: true, message: "收货信息不能为空" }
        ],
        products: [
          { required: true, message: "商品不能为空" }
        ],
        
      }
    };
  },
  created() {
     this.getDicts("store_order_type").then((response) => {
      this.orderTypeOptions = response.data;
    });
    this.getDicts("store_pay_type").then((response) => {
      this.payTypeOptions = response.data;
    });
    this.getDicts("user_status").then((response) => {
      this.userStatusOptions = response.data;
    });
    this.getDicts("store_order_status").then((response) => {
      this.statusOptions = response.data;
      console.log(response.data)
    });
    this.getDicts("store_order_delivery_status").then((response) => {
      this.deliveryStatusOptions = response.data;
    });
    this.getDicts("store_delivery_pay_status").then((response) => {
      this.deliveryPayStatusOptions = response.data;
    });
    
    this.getList();
  },
  methods: {
    handleGenPayUrl(row){
      this.payQr.open=true;
      setTimeout(() => {
        var qrcode = new QRCode(this.$refs.qrCodeUrl, {
            text: config.payQRUrl+row.id, // 需要转换为二维码的内容
            width: 200,
            height: 200,
            colorDark: '#000000',
            colorLight: '#ffffff',
            correctLevel: QRCode.CorrectLevel.H
        })
      }, 200);
      

    },
    handleAddUser(){
      this.user.open=true;
    },
    handleAddUserAddress(){
      if(this.form.userId==null){
        this.msgError("请选择会员");
        return;
      }
      this.userAddress.open=true;
      setTimeout(() => {
        this.$refs.addUserAddress.init(this.form.userId);
      }, 500);
    },
    addUser(){
      this.user.open=false;
    },
    addUserAddress(){
      this.userAddress.open=false;
      //获取地址
      this.getAddressList(this.form.userId);
    },
    compute(){
      this.totalMoney=0;
      var that=this;
      this.products.forEach (function (value) {
          that.totalMoney += value.money;
      });
      console.log(that.totalMoney)
    },
    handleProductCountChange(row){
      this.tablekey = !this.tablekey
      console.log(row)
      row.money=row.count*row.price;
      this.$forceUpdate();
      this.compute();
    },
    selectProduct(row){
      console.log(row);
      for(var i=0;i<this.products.length;i++){
        if(this.products[i].id==row.id){
          return;
        }
      }
      row.count=1;
      row.money=row.count*row.price;
      this.products.push(row);
      this.compute();
    },
    handleAddProduct(){
      this.product.open=true;
    },
    searchUser(){
      if(this.phone==null||this.phone==""){
        return;
      }
      var data={phone:this.phone}
      this.userloading = true;
      this.users=[];
      this.address=[];
      getUserList(data).then(response => {
        this.users = response.data;
        this.userloading = false;
        if(this.users!=null&&this.users.length==1){
          this.form.userId=this.users[0].userId;
          this.getAddressList(this.form.userId)
        }
      });
    },
    getAddressList(userId){
      var data={userId:userId}
      this.addressloading = true;
      this.address=[];
      getAddressList(data).then(response => {
        this.address = response.data;
        this.addressloading = false;
      });
    },
    handleDetails(row){
      this.show.open=true;
      const orderId = row.id ;
      setTimeout(() => {
        this.$refs.order.getOrder(orderId);
      }, 500);
    },
    handleClick(tab, event) {
       if(tab.name=="all"){
        this.queryParams.status==null;
      }
      else{
         this.queryParams.status=tab.name;
      }
      this.getList();
    },
    /** 查询订单列表 */
    getList() {
      if(this.queryParams.status=='00'){
        this.queryParams.status=null;
      }
      if(this.createTimeRange!=null&&this.createTimeRange.length==2){
        this.queryParams.createTimeRange=this.createTimeRange[0]+"--"+this.createTimeRange[1]
      }
      else{
        this.queryParams.createTimeRange=null;
      }
      if(this.payTimeRange!=null&this.payTimeRange.length==2){
        this.queryParams.payTimeRange=this.payTimeRange[0]+"--"+this.payTimeRange[1]
      }
      else{
        this.queryParams.payTimeRange=null;
      }
      if(this.deliveryImportTimeRange!=null&&this.deliveryImportTimeRange.length==2){
        this.queryParams.deliveryImportTimeRange=this.deliveryImportTimeRange[0]+"--"+this.deliveryImportTimeRange[1]
      }
      else{
        this.queryParams.deliveryImportTimeRange=null;
      }
      this.loading = true;
      myListStoreOrder(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.storeOrderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        addressId:null,
        userId:null,
        products: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
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "创建订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getStoreOrder(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改订单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if(this.products.length==0){
          this.msgError("请选择商品");
          return;
        }
        this.form.products=this.products;
        if (valid) {
          console.log(this.form);
          createUserOrder(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess("创建成功");
              this.open = false;
              this.getList();
            }
          });
       
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
       this.products.splice(this.products.findIndex(item => item.id === row.id), 1)
       this.compute();
       
    },
    /** 导出按钮操作 */
    handleExport() {

      if(this.queryParams.status=='00'){
        this.queryParams.status=null;
      }
      if(this.createTimeRange!=null&&this.createTimeRange.length==2){
        this.queryParams.createTimeRange=this.createTimeRange[0]+"--"+this.createTimeRange[1]
      }
      else{
        this.queryParams.createTimeRange=null;
      }
      if(this.payTimeRange!=null&this.payTimeRange.length==2){
        this.queryParams.payTimeRange=this.payTimeRange[0]+"--"+this.payTimeRange[1]
      }
      else{
        this.queryParams.payTimeRange=null;
      }
      if(this.deliveryImportTimeRange!=null&&this.deliveryImportTimeRange.length==2){
        this.queryParams.deliveryImportTimeRange=this.deliveryImportTimeRange[0]+"--"+this.deliveryImportTimeRange[1]
      }
      else{
        this.queryParams.deliveryImportTimeRange=null;
      }

      const queryParams = this.addDateRange(this.queryParams, this.dateRange);
      this.$confirm('是否确认导出所有订单数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportStoreOrder(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    handleExportItems() {
      if(this.queryParams.status=='00'){
        this.queryParams.status=null;
      }
      if(this.createTimeRange!=null&&this.createTimeRange.length==2){
        this.queryParams.createTimeRange=this.createTimeRange[0]+"--"+this.createTimeRange[1]
      }
      else{
        this.queryParams.createTimeRange=null;
      }
      if(this.payTimeRange!=null&this.payTimeRange.length==2){
        this.queryParams.payTimeRange=this.payTimeRange[0]+"--"+this.payTimeRange[1]
      }
      else{
        this.queryParams.payTimeRange=null;
      }
      if(this.deliveryImportTimeRange!=null&&this.deliveryImportTimeRange.length==2){
        this.queryParams.deliveryImportTimeRange=this.deliveryImportTimeRange[0]+"--"+this.deliveryImportTimeRange[1]
      }
      else{
        this.queryParams.deliveryImportTimeRange=null;
      }
      const queryParams = this.addDateRange(this.queryParams, this.dateRange);
      this.$confirm('是否确认导出所有订单明细数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportStoreOrderItems(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    }
  }
};
</script>
<style scoped lang="scss">
.items{
  margin: 5px 0px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
  .pic{
    width:60px;
    height:60px;
  }
  .goods-content{
    margin-left: 10px;
    max-width: 200px;
    text-align: left;
    .goods-title{
      
      overflow:hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      -o-text-overflow:ellipsis;
    }
  }
}
</style>
