<template>
  <div v-loading="loading" class="orderList">
    <div class="white-box">
      <div class="filter-box">
        <filter-user :filter-types="filterTypes" @select-value="handleFilterUser"></filter-user>
      </div>
      <el-table ref="multipleTable" :data="tableData" style="width: 100%;"
                :row-class-name="rowClassName"
                @selection-change="handleSelectionChange"
                @cell-click="openLogisticsQuery"
                :height="tool.getTableHeight()">
        <el-table-column type="selection" width="70" v-if="tableHeaders"></el-table-column>
        <el-table-column v-for="(tableHeader, key) in tableHeaders" :key="key" :label="tableHeader.header" :width="tableHeader.other.width ? tableHeader.other.width : ''" :prop="tableHeader.other.prop ? tableHeader.other.prop : null">
          <template slot-scope="scope">
            <template v-if="scope.row[tableHeader.index].other.tag" >
              <el-tag :type="scope.row[tableHeader.index].other.tag.type ? scope.row[tableHeader.index].other.tag.type : null" :size="scope.row[tableHeader.index].other.tag.size ? scope.row[tableHeader.index].other.tag.size : null" :class="scope.row[tableHeader.index].other.tag.class ? scope.row[tableHeader.index].other.tag.class : null" >{{scope.row[tableHeader.index].value}}</el-tag>
            </template>
            <template v-else>
              <div v-html="scope.row[tableHeader.index].value"></div>
            </template>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="180">
          <template slot-scope="scope">
            <el-dropdown size="small" trigger="click">
              <el-button type="primary" size="small" @click.stop="">
                操作该数据<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="edit" @click.native="handleDel(scope.row)" v-if="permission.hasPermission(`shop/edit`)">删除订单</el-dropdown-item>
                <el-dropdown-item command="edit" @click.native="handleEdit(scope.row)" v-if="permission.hasPermission(`shop/edit`)">编辑订单</el-dropdown-item>
                <el-dropdown-item command="delivery" @click.native="handleShowDeliveryDialog(scope.row)" v-if="permission.hasPermission(`shop/order-delivery`) && scope.row['STATUS'] === '1' && scope.row['DELIVERY_STATUS'] === '0' ">发货</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      <div class="white-box-footer">
        <el-button type="success" size="small" @click="handleExport" v-show="permission.hasPermission(`shop/order-list-export`)">导出Excel</el-button>
        <pagination :total="totalCount" :page_size="pageSize" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"></pagination>
      </div>
    </div>

    <el-dialog title="发货" :visible.sync="dialogDeliveryVisible">
      <el-form :model="deliveryForm" label-width="150px" class="form-dialog">
        <el-form-item label="快递公司">
          <el-input v-model="deliveryForm.expressCompany"></el-input>
        </el-form-item>
        <el-form-item label="快递单号">
          <el-input v-model="deliveryForm.orderTrackNo"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogDeliveryVisible = false">取 消</el-button>
        <el-button type="primary" @click.native="handleDelivery">发货</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :width="dialogWidth"
      custom-class="logisticsQueryDialog"
      title="物流动态"
      :visible.sync="logisticsQueryDialog"
      :before-close="logisticsQueryDialogHandleClose">
      <div class="diaBody" v-loading="logisticsQueryLoading">
        <el-tabs style="width: 100%!important" type="border-card" v-if="logisticsQueryList.length > 0">
          <el-tab-pane  v-for="( item, index ) in logisticsQueryList" :key="index" :label="item.name">
            <div class="block">
              <el-timeline :reverse="reverse">
                <el-timeline-item
                  v-for="(activity, index2) in item.children"
                  :key="index2"
                  :icon="activity.icon"
                  :color="activity.color"
                  :size="activity.size"
                  :timestamp="activity.date_action">
                  <span class="timelineStatus">{{activity.order_status}}</span>
                </el-timeline-item>
              </el-timeline>
            </div>

          </el-tab-pane>
        </el-tabs>
        <el-empty v-if="logisticsQueryEmpty" :image-size="200"></el-empty>

        <!--        <span slot="footer" class="dialog-footer">-->
        <!--          <el-button @click="dialogVisible = false">取 消</el-button>-->
        <!--        <el-button type="primary" @click="logisticsQueryDialog = false">确 定</el-button>-->
        <!--      </span>-->
      </div>

    </el-dialog>
  </div>
</template>

<script>
import FilterUser from '@/components/FilterUser'
import Pagination from '@/components/Pagination'
import filterHelper from '@/utils/filterHelper'
import network from '@/utils/network'
import permission from '@/utils/permission'
import tool from '@/utils/tool'
import axios from 'axios'

export default {
  name: 'shop_order-list',
  components: {FilterUser, Pagination},
  data () {
    return {
      tableHeaders: null,
      tableData: null,
      tableHeight: window.innerHeight - 310,
      loading: true,
      multipleSelection: [],
      currentPage: 1,
      totalPages: 1,
      totalCount: 1,
      pageSize: 20,
      tool: tool,
      permission: permission,
      filterTypes: null,
      filterModel: {},
      dialogDeliveryVisible: false,
      deliveryForm: {
        sn: '',
        expressCompany: '',
        orderTrackNo: '',
      },
      logisticsQueryDialog: false,
      logisticsQueryList: [],
      logisticsQueryLoading: false,
      reverse: true,
      logisticsQueryEmpty: false,
      dialogWidth:0,
      dialogTop:0
    }
  },
  created() {
    this.setDialogWidth()
  },
  mounted() {
    this.getData()
    window.onresize = () => {
      return (() => {
        this.setDialogWidth()
      })()
    }
  },
  methods: {
    setDialogWidth() {
      var val = document.body.clientWidth
      const def = 800 // 默认宽度
      if (val > def) {
        this.dialogWidth = '60%'
        this.dialogTop = '15vh'
      } else {
        this.dialogWidth = '90%'
        this.dialogTop = '1vh'
      }
    },
    openLogisticsQuery(row, column, cell, event){
      this.logisticsQueryEmpty = false

      if(column.label == "订单号"){
        console.log(row.SEND_AT.value , row.STATUS, row.PAY_TYPE.value )
        if((row.SEND_AT.value > 0 && row.STATUS == '1') === false ) return
        let id = row.SN.value
        this.logisticsQueryList = []
        this.logisticsQueryDialog = true
        this.logisticsQueryLoading = true
        this.queryData(id).then(res => {
          const data = res.data.data
          let keysList = Object.keys(data)
          let list = []
          keysList.forEach((key, index) => {
            let oneList = data[key]
            oneList[ oneList.length - 1 ].color = '#0bbd87'
            oneList[ oneList.length - 1 ].size = 'large'
            // oneList[ oneList.length - 1 ].icon = 'el-icon-s-promotion'
            let one = {
              'name': key,
              'children': oneList
            }
            list.push(one)
          })
          console.log(list)
          this.logisticsQueryList = list
          this.logisticsQueryLoading = false
        }).catch((error) =>{
          console.log(error);
          this.logisticsQueryList = []
          this.logisticsQueryEmpty = true
          this.logisticsQueryLoading = false
        })
      }
    },
    openLogisticsQuery1 (data) {

    },
    async queryData (id) {
      const link = 'https://taoplus.com.my/index.php?route=information/order_tracking/jsons&order_tracking_search=' + id
      const ret = await axios.get(link)// await 后面也可以跟的是Promise实例对象
      // console.log(ret)
      return ret
    },
    logisticsQueryDialogHandleClose (done) {
      this.logisticsQueryDialog = false
    },

    rowClassName (val) {
      if (val.row) {
        let index = this.multipleSelection.findIndex(item => {
          return item.ID == val.row.ID
        })
        if (index >= 0) {
          return 'selected-row'
        }
      } else {
        return ''
      }
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
      this.rowClassName(val)
    },
    handleCurrentChange (page) {
      this.getData(page, this.pageSize)
    },
    handleSizeChange (pageSize) {
      this.getData(this.currentPage, pageSize)
    },
    handleFilterUser (filterData) {
      filterHelper.handleFilterUser(this, filterData)
    },
    getData (page, pageSize) {
      let filterData = this.filterModel
      network.getPageData(this, 'shop/order-list', page, pageSize, filterData, response => {
        this.filterTypes = response.filterTypes
        this.allData = response
      })
    },
    handleExport () {
      this.$confirm(`确定要导出当前数据吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return network.getData(`shop/order-list-export`, this.filterModel)
      }).then(response => {
        this.$message({
          message: response,
          type: 'success'
        })
      }).catch(response => {

      })
    },
    handleEdit () {
      // 进入修改订单页面
    },
    handleDel (row) {
      let orderSn = row.SN.value // order订单表的编号
      this.$confirm(`确定要删除订单：${orderSn}吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 删除订单
        let postData = {
          orderSn
        }
        return network.postData('shop/delete-order', postData).then(response => {
          this.$message({
            message: response,
            type: 'success'
          })
          this.submitButtonStat = false
          this.$router.go(-1)
        }).catch(() => {
          this.submitButtonStat = false
        })
      }).then(response => {

      }).catch(response => {

      })
    },
    // 显示发货对话框
    handleShowDeliveryDialog (row) {
      this.dialogDeliveryVisible = true
      this.deliveryForm.sn = row['SN'].value
    },
    // 发货
    handleDelivery () {
      network.postData('shop/order-delivery', this.deliveryForm).then(response => {
        this.$message({
          message: response,
          type: 'success'
        })
        this.dialogDeliveryVisible = false
        this.getData(this.currentPage, this.pageSize)
      }).catch(response => {
        this.dialogDeliveryVisible = false
      })
    }
  }
}

</script>

<style scoped>
::v-deep.el-table .selected-row {
  background: #bce5ef;
  /*color: white;*/
}
.timelineStatus{
  color: #409EFF;
}
.diaBody{
  min-height: 20vh;
}
</style>
