<template>
<section class="main">

	<div class="p_all_20" v-loading="tableLoading">
    <order-search
    ref="searchnav"
    :search-param="searchParam"
    :exportmain-url="'/api/order/exportMain'"
    :exportdetail-url="'/api/order/exportDetail'"
    :brandType="1"
    @backData="backData"></order-search>

       <el-tabs  @tab-click="handleClick" v-model="activeStatus">
            <el-tab-pane :label="item.labelText" :name="item.status" v-for="(item,index) in tabList" :key="index">
                  <el-table style="width: 100%" class="TableTitle" >
                   <el-table-column
                      :label="item.labelName"
                      :width="item.widthVal"
                      align="center"
                      v-for="(item,index) in TableTitleValue" :key="index"
                    >
                    </el-table-column>
                </el-table>
            </el-tab-pane>
        </el-tabs>
         <div class="ListWrap">
            <div class="dataNo" v-show="!dataList.length">暂无数据</div>
            <!-- @mouseenter="mouseenter(index,item.flag)" @mouseleave="mouseleave(index,item.flag)" -->
            <div class="divLine" v-for="(item,index) in dataList" :key="index" v-show="dataList.length" >
              <div class="orderOption">
                <div class="left">
                    <span class="spanMright">订单编号：{{item.orderCode}}</span>
                    <span class="spanMright">下单时间：{{item.addDate}}</span>
                    <!-- v-if="item.settleStatus == 1 && item.status == 0" -->

                      <!-- 确认发货 v-if="item.settleStatus==1 && item.status == 1" -->

                      <span class="spanMright">交货期：{{item.deliveryDateStatusDesc}}
                        <i v-if="!item.lookFlag" style="display: inline-block;vertical-align: text-top;background: #F56C6C;width:8px;height: 8px;border-radius:100%;"></i>
                      </span>
                </div>
                <div class="right">
                  <el-tooltip content="商家备注" placement="right" effect="light">
                  <i
                  @click="showRemark(item.orderId,item.supplierRemark)"
                  size="medium"
                  class="el-icon-tickets"
                  :style="{'color':item.supplierRemark?'#409EFF':'','line-height':'28px','cursor': 'pointer','font-size':'18px'}"></i>

                  </el-tooltip>
                </div>
              </div>
              <el-table
                  tooltip-effect="dark"
                  style="width: 100%"
                  :data="dataList[index].details"
                  :show-header="false"
                  border
                  :span-method="objectSpanMethod"
                  :cell-class-name="tableRowClassName"

                  >
                      <el-table-column
                        align="center"
                        label="商品"
                        :width="widthSizeObj.productWidth"
                        >
                        <template slot-scope="scope">
                          <div class="goodsInfo" v-if="scope.row.skuId" @click="goProdetail(scope.row.skuId)">
                            <div class="goodsimg">
                              <img :src="scope.row.goodsImg + '?x-oss-process=image/resize,h_200,w_200'" alt="">
                            </div>
                            <div>
                           <div class="goodstext blueColor ellipsis_4" style="line-height:24px;">
                              {{scope.row.goodsInfo}} ({{scope.row.specStr}})
                            </div>
                            <div v-if="false">
                              <img v-if="scope.row.etaoProductTypeIcon" style="width:30px;" :src="scope.row.etaoProductTypeIcon" alt="">
                              <img v-else style="width:30px;" :src="scope.row.etaoProductVipIcon" alt="">
                            </div>
                            </div>

                          </div>
                          <div class="goodsInfo" v-else>
                            <div class="goodsimg">
                              <img :src="scope.row.goodsImg + '?x-oss-process=image/resize,h_200,w_200'" alt="">
                            </div>
                            <div>
                              <div class="goodstext ellipsis_4" style="line-height:24px;">
                                {{scope.row.goodsInfo}} ({{scope.row.specStr}})
                              </div>
                              <div v-if="false">
                                <img v-if="scope.row.etaoProductTypeIcon" style="width:30px;" :src="scope.row.etaoProductTypeIcon" alt="">
                                <img v-else style="width:30px;" :src="scope.row.etaoProductVipIcon" alt="">
                              </div>
                            </div>
                          </div>
                        </template>
                      </el-table-column>
                      <el-table-column
                    label="结算单价(元)"
                    align="center"
                    :width="widthSizeObj.numberWidth">
                    <template slot-scope="scope">
                      <span>{{scope.row.settlePrice}}</span>
                      <el-tooltip class="item " effect="light" placement="top-start" >
                        <div slot="content">
                          <div v-for="(item,i) in scope.row.labels" :key="i">
                            {{scope.row.labels[i]}}
                          </div>
                          </div>
                        <span class="el-icon-question"></span>
                      </el-tooltip>
                      <div v-if="scope.row.hasRefund">
                      <span class="redColor el-icon-time" @click="goRefund(scope.row.refundId,scope.row.onlyShowRefundDesc)">{{scope.row.refundStatusDesc}}</span>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="count"
                    label="数量"
                    align="center"
                    :width="widthSizeObj.numberWidth">
                  </el-table-column>
                  <el-table-column
                    label="买家"
                    align="center"
                    :width="widthSizeObj.receiverWidth">
                    <template slot-scope="scope">
                      <!-- <span>{{item.userInfo?item.userInfo.userName:''}}</span> -->
                      <span>{{item.buyerName}}</span>
                    </template>
                  </el-table-column>

                  <el-table-column
                    prop="refundStatusDesc"
                    label="商品状态"
                    align="center"
                    :width="widthSizeObj.numberWidth">
                  </el-table-column>

                  <el-table-column
                    label="交易状态"
                    align="center"
                    :width="widthSizeObj.dealWidth"
                    show-overflow-tooltip>
                    <template slot-scope="scope">
                       <div :style="{color:item.orderStatusDesc=='已完成'?'#12b34e':''}">{{item.orderStatusDesc}}</div>
                      <div class="m6"><span class="spanMright blueColor"
                      @click="goOrderDetail(item.orderId,item.allRefundStatus)">详情</span></div>
                      <div class="redColor" v-if="item.delayImgPath && item.showDelayInfo" @click="showImgFun(item.delayImgPath)">延迟发货凭证图</div>
                       <el-button size="mini" type="primary" v-if="item.canConfirm"
                      @click="confirmOrder"
                      :msn="item.confirmTips"
                      :orderid="item.orderId"
                      :idx="index"
                      v-show="item.allRefundStatus" class="confirmBtn">确认订单</el-button>
                       <el-button size="mini" type="primary" v-if="item.canDeliver"
                      @click="showSendDialog($event,item)"
                      :msn="item.deliverTips"
                      :orderid="item.orderId"
                      :showDelayInfo="item.showDelayInfo"
                      :delayImgPath="item.delayImgPath"
                      :idx="index" v-show="item.allRefundStatus">确认发货</el-button>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="结算金额(元)"
                    align="center"
                    :width="widthSizeObj.numberWidth"
                    >
                    <template slot-scope="scope">
                        <div>
                          {{item.totalSettlePrice}}
                        </div>
                        <div v-if="item.showDelayInfo==1" class="redColor">
                            {{item.delayInfo}}
                        </div>
                    </template>
                  </el-table-column>

            </el-table>
            </div>
            </div>
          <div class="pagination">
          <pagination @eventSizeChange="eventSizeChange" @eventCurrentChange="eventCurrentChange"
          :total="total" :pageSize="searchParam.pageSize" :currentPage="searchParam.pageNum"></pagination>

          </div>
  </div>

  <orderSendDialog :objProps="objProps"  @resData="cancelForm"></orderSendDialog>
  <orderRemark v-if="objPropsRemark.dialogFormVisible" :objProps="objPropsRemark"  @resData="cancelFormRemark"></orderRemark>
   <el-dialog :visible.sync="dialogVisible" :modal="false">
    <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
</section>

</template>

<script>
import { mapState,mapMutations } from 'vuex'
import qs from 'qs'
import orderSendDialog from '@/components/common/orderSendDialog.vue'
import pagination from "@/components/common/pagination"
import orderSearch from '@/components/common/orderSearch'
import orderRemark from '@/components/common/orderRemark'


import {getOrderRowColum,osmethod,_getStorage,_saveStorage,_removeStorage } from '@/utils/utils'
// import { close } from 'fs';
  export default {
      name: 'orderlist',
      data() {
          return {
            dialogVisible:false,
            dialogImageUrl:'',
            noGet:false,
            listType:'',
            tableLoading: false,
            widthSizeObj:'', // 宽度配置
            objProps:{
              dialogFormVisible:false,
              orderid:'',
              url:'/order/deliver', //发货路径
              showDelayInfo:0,
              delayImgPath:""
            },
            objPropsRemark:{
              dialogFormVisible:false,
              orderid:'',
              supplierRemark:'',
              url:'/order/supplierremark', //商家备注
            },


          activeStatus: '-1',
          total:0,
          multipleSelection: [],
         searchParam: {
          orderCode: '',
          brandId: '',
          actType: '',
          invoiceNo: '',
          receiver:'',
          deliveryDateStatus:'',
          addDateBegin:'',
          addDateEnd:'',
          completionDateBegin:'',
          completionDateEnd:'',
          pageNum:1,
          pageSize:10,
          status:'-1',
          goodsName:'',
          logisticsName:''

        },
        // addDateVal:[],//日期选择范围
        // cptDateVal:[],//日期选择范围
        tabList:[{
                    labelText:'全部订单',
                    name:'order_all',
                    status:'-1',
                  },
          {
                    labelText:'待付款',
                    name:'order_waitPay',
                    status:'0',
                  },
          {
                    labelText:'待确认',
                    name:'order_waitConfirm',
                    status:'1',
                  },{
                    labelText:'待发货',
                    name:'order_waitSend',
                    status:'2',
                  },{
                    labelText:'已发货',
                    name:'order_haveSend',
                    status:'3',
                  },{
                    labelText:'已成功',
                    name:'order_done',
                    status:'4',
                  },{
                    labelText:'已关闭',
                    name:'order_close',
                    status:'5',
                  },{
                    labelText:'退款中',
                    name:'order_refund',
                    status:'6',
                  },
                  // {
                  //   labelText:'异常订单',
                  //   name:'order_exorder',
                  //   status:'7',
                  // }
                  ],
        dataList:[],
        orderIndexArr:[],
        hoverOrderArr:[],
        rowIndex: '-1',
        TableTitleValue:[
          {labelName:"商品",widthVal:this.widthSize.productWidth},
          {labelName:"结算单价(元)",widthVal:this.widthSize.numberWidth},
          {labelName:"数量",widthVal:this.widthSize.numberWidth},
          {labelName:"买家",widthVal:this.widthSize.receiverWidth},
          {labelName:"商品状态",widthVal:this.widthSize.numberWidth},
          {labelName:"交易状态",widthVal:this.widthSize.dealWidth},
          {labelName:"结算金额(元)",widthVal:this.widthSize.numberWidth},

        ]
      };
      },
      components:{
        orderSendDialog,
        pagination,
        orderSearch,
        orderRemark

      },
      computed:{

      },
      mounted(){
       this.widthSizeObj = this.widthSize;//宽度配置
       //订单状态
       this.listType = this.$route.params.type?this.$route.params.type:'-1';

       //首页跳进来的订单状态
       if(this.listType){
         this.activeStatus = this.listType+''
       }
    },

    methods: {
      ...mapMutations("navBar",['getOrderTimeOutTip']),
      showImgFun(url){
          this.dialogVisible=true
          this.dialogImageUrl=url
      },
      backData(res){
          this.getOrderList();
      },
         eventSizeChange(val) {
          this.searchParam.pageSize = val;
          this.getOrderList();
        },
        eventCurrentChange(val) {
          this.searchParam.pageNum = val;
          this.getOrderList();
        },

        //鼠标上移
        mouseenter(index,flag){
          this.dataList[index]["flag"] == 0?this.dataList[index]["flag"] = 100 :''
        },
        mouseleave(index,flag){
          this.dataList[index]["flag"] == 100?this.dataList[index]["flag"] = 0 :''
        },

        getOrderList() {
            this.tableLoading = true;
            let { brandId } = _getStorage('info');
            this.searchParam.brandId =brandId;
            var params = this.searchParam;
            params.status = ~~this.activeStatus;
            this.$axios.get('/order/list',{
              params
            }).then((res) => {
              this.tableLoading = false;
              if(res.data.code==200){
                 let list = res.data.data.list;
                 this.dataList = list;
                 this.total = ~~res.data.data.total;
                this.isAllRefund();
                this.orderIndexArr = getOrderRowColum(list);
              }else{
                this.$message.error(res.data.message);
              }

            }).catch(()=>{
              this.tableLoading = false;
            })
        },
        //订单状态数量统计
        getOrderStats(){
          this.$axios.get('/order/stats').then((res) => {
              if(res.data.code==200){
                let orderStats = res.data.data;
                let tabLists = [];
                tabLists = [{
                    labelText:'全部订单',
                    name:'order_all',
                    status:'-1',
                  },{
                    labelText:'待付款' +"("+ orderStats.waitPay+ ")",
                    name:'order_waitPay',
                    status:'0',
                  },{
                    labelText:'待确认' +"("+ orderStats.waitConfirm+ ")",
                    name:'order_waitConfirm',
                    status:'1',
                  },{
                    labelText:'待发货' +"("+ orderStats.waitDeliver+ ")",
                    name:'order_waitSend',
                    status:'2',
                  },{
                    labelText:'已发货'+"("+ orderStats.delivered+ ")",
                    name:'order_haveSend',
                    status:'3',
                  },{
                    labelText:'已成功'+"("+ orderStats.finish+ ")",
                    name:'order_done',
                    status:'4',
                  },{
                    labelText:'已关闭'+"("+ orderStats.cancel+ ")",
                    name:'order_close',
                    status:'5',
                  },{
                    labelText:'退款中'+"("+ orderStats.refunding+ ")",
                    name:'order_refund',
                    status:'6',
                  },{
                    labelText:'异常订单',
                    name:'order_exorder',
                    status:'7',
                  }];
                this.tabList = tabLists;
              }else{
                this.$message.error(res.data.message);
              }

            }).catch(()=>{})
        },

        //合并行
        objectSpanMethod({ row, column, rowIndex, columnIndex }) {

          if(this.orderIndexArr.length>0){
            if (columnIndex === 3 || columnIndex === 5 || columnIndex === 6) {
              return osmethod(this.orderIndexArr,rowIndex)
            }
          }
        },

      //默认行的样式
      tableRowClassName({row,rowIndex}) {
         return 'hovered-row'
      },
      //所有明细都退款成功或已确认退款，隐藏确认订单和发货按钮。因为需要平台确认后才真正改变订单状态。
      isAllRefund(){
        const dataLen = this.dataList.length;
        const refundCount = [];
        const detailsLen = [];
        for(var i = 0; i<dataLen;i++){
          const deLen = this.dataList[i].details && this.dataList[i].details.length;
          this.dataList[i].allRefundStatus = true;
          let aa = this.dataList[i].details.length;

          detailsLen.push(aa);

          for(var j=0;j<deLen;j++){
            let re = this.dataList[i].details[j].refund;
            refundCount[i] = [];
            if(re && (re.status==3 || re.auditStatus==1)){
                  refundCount[i][j] = j;
            }
          }

        }
          for(let a = 0;a<refundCount.length;a++){
            for(let b =0;b<detailsLen.length; b++){
              if(a===b){
                if(refundCount[a].length === detailsLen[b]){
                  this.dataList[a].allRefundStatus=false
                }
              }
            }
          }
        // console.log('detailsLen--',detailsLen);
        // console.log('refundCount---',refundCount)
      },

      handleClick(tab, event) {
        this.activeStatus = tab.name;
         this.searchParam = {
          orderCode: '',
          brandId: '',
          actType: '',
          invoiceNo: '',
          receiver:'',
          deliveryDateStatus:'',
          addDateBegin:'',
          addDateEnd:'',
          completionDateBegin:'',
          completionDateEnd:'',
          pageNum:1,
          pageSize:10,
          status:'-1',
          goodsName:'',
          logisticsName:''

        },
        this.searchParam.pageNum = 1;
        this.searchParam.pageSize = 10;
        this.searchParam.status = parseInt(tab.name);
        this.$refs.searchnav.addDateVal ='';
        this.$refs.searchnav.cptDateVal ='';

        // this.getOrderList();
        if(this.activeStatus == '-1'){
            this.$router.push({ path: '/order/orderlist'})
        }else{
            this.$router.push({ path: '/order/orderlist/' + this.activeStatus,})
        }

      },
      goOrderDetail(orderid,isAllrefund){
         var isAllrefund = !isAllrefund?1:0
        var orderid = orderid;
           this.$router.push({ path: '/order/frmOrderDetail', query:{
            orderid:orderid,
            isAllrefund:isAllrefund
          }})
          // let routeUrl = this.$router.resolve({
          //       path: "/order/frmOrderDetail",
          //       query: {
          //         orderid:orderid,
          //         isAllrefund:isAllrefund
          //       }
          // });
          // window.open(routeUrl .href, '_blank');

      },
      goRefund(refundId,onlyShowRefundDesc=0){
        if(onlyShowRefundDesc==1){
          return
        }
          // var refundId = row.refundId;
          this.$router.push({path:'/order/refundProcessing',query:{refundId:refundId}})
        },
      //订单中有商品退款中状态时，多一层提示框。
      isConfirmRefund(index){
        const idxList= this.dataList[index];
        let len = idxList.details.length;
        let arr =[];
        for(let i=0;i<len;i++){
            if(idxList.details[i].refund!=null&&idxList.details[i].refund.status==1&&idxList.details[i].refund.auditStatus!==1){
              arr.push(i);
            }
          return arr
        }
      },
        //确认订单
      confirmOrder(e){
        let idx = e.currentTarget.getAttribute("idx");
        let orderid = e.currentTarget.getAttribute("orderid");
        let msn = e.currentTarget.getAttribute("msn"); // 部分退款提示
        let refundlen = this.isConfirmRefund(idx).length;
        let data = {"orderId":orderid};
        // let dataParam = qs.stringify(data);
        if(refundlen>0){
          this.$confirm(msn, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
          this.confirmFun(data)

          }).catch(() => {

          });
        }else{
          this.confirmFun(data)

        }


      },
      confirmFun(dataParam){
      this.$confirm("确认订单?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.$axios
              .post("/order/confirm", dataParam)
              .then(res => {
                if (res.data.code == 200) {
                  this.$message.success("已确认订单");
                    this.getOrderList();
                    this.getOrderTimeOutTip()
                    // this.getOrderStats();
                } else {
                  this.$message.error(res.data.message);
                }
              })
              .catch(res => {});
          })
          .catch(() => {});
    },
      // 发货
      showSendDialog(e,item){
        //判断是否有退货商品
        let hasReturnGoods = false;
        let temRefundId = "";
        if (item.details.length > 0) {
          let detaiList = item.details;
          for (let i = 0; i < detaiList.length; i++) {
            if (detaiList[i].refundStatusDesc == "买家申请退款中") {
              hasReturnGoods = true;
              temRefundId = detaiList[i].refundId;
              break;
            }
          }
        }
        let showDelayInfo = e.currentTarget.getAttribute('showDelayInfo')
         let orderid = e.currentTarget.getAttribute("orderid");
         let idx = e.currentTarget.getAttribute("idx");
         let msn = e.currentTarget.getAttribute("msn"); // 部分退款提示
         let refundlen = this.isConfirmRefund(idx).length;
         let delayImgPath = e.currentTarget.getAttribute('delayImgPath')
        if (hasReturnGoods) {
          this.$confirm("该订单存在买家申请退款的商品，请处理完退款后再确认发货", "提示", {
            confirmButtonText: "去处理退款",
            cancelButtonText: "稍等一会",
            type: "warning",
          }).then(() => {
            this.goRefund(temRefundId)
          }).catch(() => {
          });
        } else {
          this.objProps.showDelayInfo = showDelayInfo;
          this.objProps.delayImgPath = delayImgPath;
          this.objProps.orderid = orderid;
          this.objProps.dialogFormVisible = true;
        }
      },
      cancelForm(res){
          // 接收子组件参数并赋值
          this.objProps.dialogFormVisible = res.state;
          this.getOrderList()
        },

      goProdetail(skuId){
          //  var productId = productId;
           if(skuId){
            this.$router.push({ path: '/goods/productdetails', query:{
              skuId:skuId,
            }})
          //   let routeUrl = this.$router.resolve({
          //       path: "/goods/productdetails",
          //       query: {
          //         skuId
          //       }
          //   });
          // window.open(routeUrl .href, '_blank');
           }
      },
      // 备注
      showRemark(orderid,remark){
          this.objPropsRemark.orderid = orderid;
          this.objPropsRemark.supplierRemark = remark
          this.objPropsRemark.dialogFormVisible = true;
      },
      cancelFormRemark(res){
        this.objPropsRemark.dialogFormVisible = res.state;
        this.getOrderList()
      },

    },
      activated() {
        // console.log('this.$route.meta.isBack--',this.$route.meta.isBack);
      if (!this.$route.meta.isBack) {
          this.listType = this.$route.params.type?this.$route.params.type:'-1';
          //首页跳进来的订单状态
          if(this.listType){
            this.activeStatus = this.listType+''
          }
          this.searchParam.pageNum = 1;
           this.getOrderList();
        }
        this.$route.meta.isBack = false;
      },
      beforeRouteEnter(to, from, next) {
          if ((from.path == "/order/frmOrderDetail") || (from.path =='/goods/productdetails') || (from.path == '/order/refundProcessing')) {
            to.meta.isBack = true;
          } else {
            to.meta.isBack = false;
          }

          next();
      },
    watch:{
          //监听相同路由下参数变化的时候，从而实现异步刷新
          '$route'(to,from) {

                this.listType = this.$route.params.type?this.$route.params.type:'-1';

                if(from.path.indexOf('/order/orderlist') != -1 && to.path.indexOf('/order/orderlist') != -1){
                    this.activeStatus = this.listType+'';
                    this.searchParam.pageNum =1
                    this.getOrderList();
                }
                if(from.path == '/order/frmOrderDetail' || from.path =='/goods/productdetails' || from.path == '/order/refundProcessing'){
                  if(this.activeStatus != this.listType){
                     this.activeStatus = this.listType+'';
                      this.searchParam.pageNum =1
                    }
                  this.getOrderList();
                }

              // if(this.$route.query.activeStatus){
              //     this.activeStatus = this.$route.query.activeStatus + '';
              //     this.getOrderList();
              // }

          }
     },
  }

</script>

<style lang="scss" scoped="scoped">
@import '@/assets/styles/order.scss';

</style>

