<!-- 商家订单管理 -->
<template>
    <div class="execution">
        <basic-container>
            <avue-crud ref="crud"
                       :page.sync="page"
                       :data="tableData"
                       :permission="permissionList"
                       :table-loading="tableLoading"
                       :option="tableOption"
                       @on-load="getList"
                       @search-change="searchChange"
                       @refresh-change="refreshChange"
                       @size-change="sizeChange"
                       @current-change="currentChange"
                       @row-update="handleUpdate"
                       @row-save="handleSave"
                       @row-del="handleDel">
              <!--  1.行内按钮-->
              <template slot-scope="scope" slot="menu">
                <el-button  type="button" size="small"
                            v-if="qxqAuth(scope.row)>=0"
                            @click="checkTheDetails(scope.row)" style="color: #409EFF;margin: 5px;padding: 0px;border: 0px">详情</el-button>
                <el-button  type="button" size="small"
                            v-if="qwlAuth(scope.row)>=0"
                            @click="viewLogistics(scope.row)" style="color: #409EFF;margin: 5px;padding: 0px;border: 0px">查看物流</el-button>
                <el-button type="button" size="small"
                           v-if="ljfhAuth(scope.row)>=0"
                           @click="shipsImmediately(scope.row)" style="color: #409EFF;margin: 5px;padding: 0px;border: 0px">立即发货</el-button>
                <el-button type="button" size="small"
                           v-if="delAuth(scope.row)>=0"
                           @click="handleDel(scope.row)" style="color: #409EFF;margin: 5px;padding: 0px;border: 0px">删除</el-button>
                <el-button type="button" size="small"
                           v-if="qxddAuth(scope.row)>=0"
                           @click="cancelOrder(scope.row)" style="color: #409EFF;margin: 5px;padding: 0px;border: 0px">取消订单</el-button>
              </template>
            </avue-crud>
        </basic-container>
      <!-- 1.取消订单 -->
      <el-dialog
        title="取消订单" :visible.sync="cancelOrderDialog" width="40%"
        :before-close="handleClose">
        <el-form ref="form" :model="orderForm">
          <el-input  type="textarea" v-model="orderForm.id" v-show="false">1111111111</el-input>
          <el-input type="textarea" v-model="orderForm.mark"></el-input>
          <el-form-item>
            <el-button type="primary" :loading="loading" @click="cancelOrder_cancel" style="float: left;margin-left: 20%;margin-top: 30px">取 消</el-button>
            <el-button type="primary" :loading="loading" @click="cancelOrder_submit" style="float: right;margin-right: 20%;margin-top: 30px">确 认</el-button>
          </el-form-item>
        </el-form>


      </el-dialog>

      <!-- 2.查看物流对话框 -->
      <el-dialog
        title="订单物流" :visible.sync="dialogVisible" width="40%"
        :before-close="handleClose">
        <p>快递单号 :{{this.form.waybillNo}}</p><p></p>
        <div class="block">
          <el-timeline>
            <el-timeline-item
              v-for="(activity, index) in activities"
              :key="index"
              :icon="activity.icon"
              :type="activity.type"
              :color="activity.color"
              :size="activity.size"
              :timestamp="activity.timestamp">
              {{activity.content}}
            </el-timeline-item>
          </el-timeline>
        </div>
      </el-dialog>

      <!-- 3.立即发货对话框 -->
      <el-dialog
        title="订单发货" :visible.sync="dialogVisibleShipsImmediately" width="40%"
        :before-close="handleClose">
        <el-form ref="form" :model="form">
            <el-form-item :initDropDownBox="initDropDownBox" label="请选择快递公司 :" prop="expressCompany" label-width="200px">
              <!-- 下拉 -->
              <el-select v-model="form.expressCompany" size="30px">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          <el-form-item  label="请填写快递单号 :" prop="waybillNo" label-width="200px">
            <el-input v-model="form.waybillNo" size="30px"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <span slot="footer" class="dialog-footer">
                <el-button type="primary" :loading="loading" @click="confirmDelivery"
                           style="width: 200px; height: 40px;display:block;margin:0 auto;" >
                  确认发货</el-button>
            </span>
      </el-dialog>

    </div>
</template>

<script>
  import {getMerchantByAccount,fetchList, shipsImmediatelyApi, delObj, cancelOrderApi, viewLogisticsApi} from '@/api/mall/merchantMallorder'
  import {tableOption} from '@/const/crud/mall/merchantMallorder'
  import {mapGetters} from 'vuex'
  import {ZmMixin} from '@/mixins/ZmMixin.js'
  export default {
      name: 'businessorder',
      mixins: [ZmMixin],

      data() {
            return {
              paymentVoucher: '',
              activities: [],// 查看物流当前状态
              options:[],// 快递公司下拉
              loading:false,
              orderForm:{
                id:'',
                mark:"请输入取消原因",
              },
              form:{
                id:0,
                expressCompany:'',//快递公司
                waybillNo:'',//快递单号
              },
                dialogVisibleShipsImmediately:false,//立即发货对话框
                dialogVisible: false,// 查看物流对话框
                dialogVisibleConfirmPayment:false,// 确认支付对话框
                cancelOrderDialog:false,
                searchForm: {},
                tableData: [],
                page: {
                    total: 0, // 总页数
                    currentPage: 1, // 当前页数
                    pageSize: 20 // 每页显示多少条
                },
                tableLoading: false,
                tableOption: tableOption
            }
        },
        // 自定义的组件
        components: {
          'cancel-order': () => import('./components/cancelOrder.vue'),
        },
        computed: {
          initDropDownBox(){
            this.$axios.get("/general/mallExpressCompany/dropDownBox/courierCompany").then(e =>{
              this.options=Object.values(e.data)
            })
          },
          ...mapGetters(['permissions']),
          permissionList() {
              return {
                  addBtn: this.vaildData(this.permissions.admin_mallorder_add, false),
                  delBtn: this.vaildData(this.permissions.admin_mallorder_del, false),
                  editBtn: this.vaildData(this.permissions.admin_mallorder_edit, false)
              };
          }
        },
        methods: {
          // 取消订单
          cancelOrder(row){
            this.orderForm.id=row.id
            this.cancelOrderDialog=true
          },
          // 取消订单-取消
          cancelOrder_cancel(){
            this.cancelOrderDialog=false
          },
          // 取消订单-确认
          cancelOrder_submit(){
            this.cancelOrderDialog=false
            if(this.orderForm.mark.length<=0){
              this.orderForm.mark='未填写备注'
              return
            }else {
              cancelOrderApi(this.orderForm).then(r => {
                this.$message.success('发货成功')
                this.getList(this.page)
              }).catch(e =>{
                console.log('错误', e.message)
              })
            }

          },
          qwlAuth: function (row) {//查看物流
            let str=row.state
            let text='4,6'//待收货，已完成
            return text.search(str)
          },
          ljfhAuth: function (row) {//立即发货
            let str=row.state
            let text='3'//待发货
            return text.search(str)
          },
          qxqAuth: function (row) {//查看详情
            let str=row.state
            let text='3,4,6,7'//待发货,待收货,已完成,已取消
            return text.search(str)
          },
          delAuth: function (row) {//删除
            let str=row.state
            let text='6,7'//已完成,已取消
            return text.search(str)
          },
          // 是否可以取消订单
          qxddAuth: function (row) {
            let str=row.state
            let text='3'
            return text.search(str)
          },
          contains: function (row) {
            let str=row.state
            let text='1,6,3,5'
            return text.search(str)
          },
          // 立即发货-对话框
          shipsImmediately(row){
            // this.form.orderNo=row.orderNo
            this.form.id=row.id
            this.$axios.get("/admin/merchantMallOrder/isNeedMailed",{
              params:{orderNo:row.orderNo},
            }).then(response => {
              console.log(JSON.stringify(response.data.data))
              if(response.data.data===true){
                console.log("需邮寄，填写信息")
                this.dialogVisibleShipsImmediately = true
              } else {
                console.log("无需邮寄，二次确认即可")
                this.$confirm('是否确认发货？', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(data => {
                  shipsImmediatelyApi(this.form).then(r => {
                    this.$message.success('发货成功')
                    this.getList(this.page)
                  }).catch(e => {
                    console.log('错误', e.message)
                  })
                })
              }
            }, error => {
              console.log('错误', error.message)
            })

          },
          // 确认发货-提交按钮
          confirmDelivery(){
              shipsImmediatelyApi(this.form).then(r => {
                this.dialogVisibleShipsImmediately = false
                this.$message.success('发货成功')
                this.getList(this.page)
                return r.data
              }).catch(e =>{
                console.log('错误', e.message)
              })

          },
          // 关闭对话框-查看物流
          handleClose(done) {done();},
          // 更改完成
          onChangeDone() {
            this.cancelOrderVue =false
            this.refreshChange()
          },
          // 查看物流-对话框
          viewLogistics(row){
            // 1.打开对话框
            this.dialogVisible = true
            this.form.waybillNo=row.waybillNo
            if(row.waybillNo==undefined){
              this.$message.error('订单数据异常,没有物流相关信息。')
              this.dialogVisible = false
            }else {
              viewLogisticsApi(
                {waybillNo:row.waybillNo,expressCompany:row.expressCompany}
              ).then(r=>{
                if(r.data.data.result==undefined){
                    this.activities.push({"content":'用户已签收',
                      "timestamp":undefined,color: '#0bbd87'})
                  }else {
                  for (let i = 0; i <r.data.data.result.list.length ; i++) {
                    if(i === 0){
                      this.activities.push({"content":r.data.data.result.list[i].status,
                        "timestamp":r.data.data.result.list[i].time,color: '#0bbd87'})
                    }else {
                      this.activities.push({"content":r.data.data.result.list[i].status,
                        "timestamp":r.data.data.result.list[i].time})
                    }
                  }
                }
              })
            }
         },
          // 查看详情
          checkTheDetails(row){
            this.$router.push('/businessOrder/details?id=' + row.id)
          },
          // 列表查询
          getList(page, params) {
            // 1.获取当前登陆用户ID
            let userInfo=  JSON.parse(sessionStorage.getItem("linshenxs-userInfo"))
            let account=userInfo.content.username
            getMerchantByAccount(
              {account: account}
            ).then(response => {
              fetchList(Object.assign({
                current: page.currentPage,
                size: page.pageSize,
                merchantId:response.data.data.id
              }, params, this.searchForm)).then(response => {
                this.tableData = response.data.data.records
                this.page.total = response.data.data.total
                this.tableLoading = false
              }).catch(() => {
                this.tableLoading = false
              })
            }).catch(() => {
              this.tableLoading = false
            })
          },
          // 删除
          handleDel: function (row, index) {
              this.$confirm('是否确认删除？', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
              }).then(function () {
                  return delObj({ids:row.orderNo})
              }).then(data => {
                  this.$message.success('删除成功')
                  this.getList(this.page)
              })
          },
          // 批量删除
          handleDelBatch() {
              if (this.$refs.crud.tableSelect.length === 0) {
                  this.$message.error('请选择项进行删除')
                  return false
              }
              let ids = []
              for (const row of this.$refs.crud.tableSelect) {
                  ids.push(row.id)
              }

              this.$confirm('是否确认删除？', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
              }).then(function () {
                  return delObj(ids)
              }).then(data => {
                  this.$notify.success('删除成功')
                  this.$refs.crud.toggleSelection();
                  this.refreshChange();
              })
          },
          // 更新
          handleUpdate: function (row, index, done,loading) {
              putObj(row).then(data => {
                  this.$message.success('修改成功')
                  done()
                  this.getList(this.page)
              }).catch(() => {
                  loading();
              });
          },
          // 保存
          handleSave: function (row, done,loading) {
              addObj(row).then(data => {
                  this.$message.success('添加成功')
                  done()
                  this.getList(this.page)
              }).catch(() => {
                  loading();
              });
          },
          // 每页条数改变事件
          sizeChange(pageSize){
              this.page.pageSize = pageSize
          },
          // 当前页发生改变事件
          currentChange(current){
              this.page.currentPage = current
          },
          // 查询事件
          searchChange(form, done) {
              this.searchForm = form
              this.page.currentPage = 0
              this.getList(this.page, form)
              done()
          },
          // 刷新事件
          refreshChange() {
              this.getList(this.page)
          },


          // queryParams(page, params) {
          //   let p = {
          //     current: page.currentPage,
          //     size: page.pageSize
          //   }
          //   if(params) {
          //     let range = this.parseRange(params)
          //     p = {
          //       ...p,
          //       startTime: range[0],
          //       endTime: range[1],
          //       goodsId: params.goodsId,
          //       shopName: params.shopName,
          //       classifyName: params.classifyId,
          //       goodsName: params.goodsName,
          //       state: params.state
          //
          //     }
          //   }
          //   return p
          // },
          // getList(page, params) {
          //   this.tableLoading = true
          //   let p = this.queryParams(page, params)
          //   fetchList(p).then(response => {
          //     this.tableData = response.data.data.records
          //     this.page.total = response.data.data.total
          //     this.tableLoading = false
          //   }).catch(() => {
          //     this.tableLoading=false
          //   })
          // },
        }
    }
</script>
