<template>
  <div class="self-draw-table-con">
    <div class="search-con">
      <Input
        placeholder="提货单号"
        class="search-input"
        v-model="searchContent.orderDeliveryId"
        clearable
        style="width: 200px"
      />
      <Input
        placeholder="用户ID"
        class="search-input"
        v-model="searchContent.uid"
        clearable
        style="width: 200px"
      />
      <Input
        placeholder="商品编号"
        class="search-input"
        v-model="searchContent.gid"
        clearable
        style="width: 200px"
      />
      <Select
        placeholder="状态"
        class="search-input"
        v-model="searchContent.deliveryState"
        style="width: 200px"
      >
        <Option value>全部</Option>
        <Option
          v-for="(item, key) of DeliveryStatus"
          :value="item"
          :key="'type-option-' + key"
          >{{ DeliveryStatusObj[item].label }}</Option
        >
      </Select>
      <ButtonGroup class="search-btngroup">
        <Button @click="handleSearch" type="primary">搜索</Button>
        <Button type="primary" @click="handleRefresh">
          <Icon type="md-refresh" />
        </Button>
      </ButtonGroup>
    </div>
    <tables
      ref="tables"
      pagable
      v-model="tableData"
      :columns="columns"
      :currentPage="searchContent.pageNum"
      :pageSize="searchContent.pageSize"
      :totalSize="totalSize"
      :loading="loading"
      @on-change="handleCurrentChange"
    />
    <Modal
      v-model="deliveryModal"
      title="审核："
      :width="400"
      class-name="vertical-center-modal"
      @on-cancel="handleCancelDelivery"
    >
      <div class="modal-item">
        <label class="label">结果：</label>
          <RadioGroup v-model="deliveryForm.isApproved">
            <Radio :label="1">
              <span>通过</span>
            </Radio>
            <Radio :label="0">
              <span>驳回</span>
            </Radio>
          </RadioGroup>
      </div>
      <div class="modal-item" v-if="deliveryState == 4">
        <label class="label">收件信息：</label>
          <Select
            placeholder="退货地址"
            style="width: 400px;"
            v-model="addressId"
          >
            <Option v-for="item in addressList" :value="item.addressId" :key="item.addressId">{{item.contactName}}/{{item.contactPhone}}/{{item.mailingAddress}}</Option>
          </Select>
      </div>
      <div class="modal-item">
        <label class="label">备注：</label>
          <Input
            placeholder="请输入..."
            v-model="deliveryForm.remark"
            type="textarea"
          />
      </div>
      <div slot="footer">
        <Button
          @click="handleDeliverySubmit"
          :loading="deliveryLoading"
          type="primary"
          long
        >确 定</Button
        >
      </div>
    </Modal>
    <Modal
      v-model="shipModal"
      title="发货："
      :width="400"
      class-name="vertical-center-modal"
      @on-cancel="handleCancelShip"
    >
      <div class="modal-item">
      <label class="label">快递渠道：</label>
        <Select
          placeholder="请选择快递渠道"
          v-model="expressType"
        >
          <Option
            v-for="(item, index) of expressCompanyList"
            :value="item.companyName"
            :key="'state-option-' + index"
          >{{item.expName}}</Option
          >
        </Select>
      </div>
      <div class="modal-item">
      <label class="label">快递单号：</label>
      <Input
        placeholder="快递编号"
        v-model="expressNo"
      />
      </div>
      <div slot="footer">
        <Button
          @click="handleShipSubmit"
          :loading="shipSubmitLoading"
          type="primary"
          long
          >确 定</Button
        >
      </div>
    </Modal>
  </div>
</template>

<script>
import Tables from '_c/tables'
import { formatTime } from '@/libs/tools'
import TableExpand from './table-expand'
import {
  DeliveryType,
  DeliveryTypeName,
  DeliveryStatus,
  DeliveryStatusObj
} from '@/enums'
export default {
  inject: ['reload'],
  components: {
    Tables,
    TableExpand
  },
  computed: {
    isBrand () {
      return this.$store.getters.isBrand
    }
  },
  data () {
    return {
      DeliveryType,
      DeliveryTypeName,
      DeliveryStatus,
      DeliveryStatusObj,

      searchContent: {
        deliveryState: '',
        gid: '',
        uid: '',
        orderDeliveryId: '',
        pageNum: 1,
        pageSize: 10
      },
      createTime: [],

      columns: [
        {
          title: '订单编号',
          key: 'orderDeliveryId',
          minWidth: 180,
          align: 'left',
          render: (h, params) => {
            return h('span', params.row.orderDeliveryId || '--')
          }
        },
        { title: '用户ID', key: 'uid', minWidth: 180, align: 'left' },
        { title: '商品编号', key: 'goodsId', minWidth: 180, align: 'left' },
        { title: '商品件数',
          key: 'number',
          width: 90,
          align: 'center'
        },
        { title: '物流单号', key: 'expressNo', minWidth: 180, align: 'left' },
        {
          title: '订单状态',
          key: 'status',
          width: 140,
          align: 'center',
          render: (h, params) => {
            let obj = DeliveryStatusObj[params.row.deliveryState] || {}
            return h('Tag', { props: { color: obj.color } }, obj.label)
          }
        },
        { title: '物流渠道', key: 'expressName', width: 120, align: 'center' },
        {
          title: '下单时间',
          width: 160,
          align: 'center',
          render: (h, params) => {
            return h('span', formatTime(params.row.createTime))
          }
        },
        // {
        //   title: '商品名称',
        //   key: 'goodsName',
        //   minWidth: 200,
        //   align: 'center',
        //   render: (h, params) => {
        //     let { goodsName, drawGoods } = params.row
        //     let label = ''
        //     if (goodsName) {
        //       label = goodsName
        //     } else {
        //       label = drawGoods.map((item) => item.goodsName).join(', ')
        //     }
        //     if (label.length > 50) {
        //       label = label.slice(0, 50) + '...'
        //     }
        //     return h('span', label)
        //   }
        // },
        // { title: '用户账号', key: 'account', minWidth: 120, align: 'center' },
        {
          title: '操作',
          minWidth: 200,
          align: 'left',
          fixed: 'right',
          render: (h, params) => {
            const emptySpan = h('span', '--')
            const shipBtn = h(
              'Button',
              {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                on: {
                  click: this.handleShip(params.row)
                },
                style: {
                  display: params.row.deliveryState == DeliveryStatus.UN_SHIP ? 'inline-block' : 'none',
                  marginRight: '10px'
                }
              },
              '发 货'
            )
            const checkBtn = h(
              'Button',
              {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                on: {
                  click: this.handleCheck(params.row)
                },
                style: {
                  display: params.row.deliveryState == DeliveryStatus.UN_REFUND ? 'inline-block' : 'none',
                  marginRight: '10px'
                }
              },
              '审 核'
            )

            const toBeSigned = h(
              'Button',
              {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                on: {
                  click: this.handleCheck(params.row)
                },
                style: {
                  display: params.row.deliveryState == DeliveryStatus.TO_BE_SIGNED ? 'inline-block' : 'none',
                  marginRight: '10px'
                }
              },
              '签 收'
            )
            const detailBtn = h(
              'Button',
              {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                on: {
                  click: this.handleDetail(params.row)
                }
              },
              '详 情'
            )

            return h('div', [shipBtn, checkBtn, toBeSigned, detailBtn])
          }
        }
      ],
      tableData: [],
      totalSize: 0,
      loading: false,

      shipModal: false,
      orderDeliveryId: '',
      expressNo: '',
      updateTime: '',
      expressType: '',
      expressRow: null,
      shipSubmitLoading: false,
      expressCompanyList: [],
      deliveryModal: false,
      deliveryForm: {
        isApproved: 1,
        orderDeliveryId: '',
        updateTime: '',
        remark: ''
      },
      addressId: '',
      // state: '',
      deliveryRules: {
        type: { required: true, message: '不能为空！', trigger: 'change' }
      },
      deliveryLoading: false,
      deliveryState: '',
      addressList: []
    }
  },
  methods: {
    requestData () {
      this.loading = true
      this.api({
        apiName: 'getPickUpList',
        postdata: this.searchContent,
        success: (res) => {
          this.totalSize = res.data.total
          this.tableData = res.data.records
        },
        complete: () => {
          this.loading = false
        }
      })
    },
    handleSearch () {
      this.searchContent.pageNum = 1
      this.requestData()
    },
    handleRefresh () {
      this.reload()
    },
    handleCurrentChange (pageNum) {
      this.searchContent.pageNum = pageNum
      this.requestData()
    },
    handleDetail (row) {
      return () => {
        // this.$Message.warning('该功能暂未开发哦！')
        let query = { orderDeliveryId: row.orderDeliveryId }
        this.$router.push({ name: 'pick_up_detail', query })
      }
    },
    handleCheck (row) {
      return () => {
        //  可以退货 toto
        this.deliveryState = row.deliveryState
        if (this.deliveryState == 4) {
          this.api({
            apiName: 'getAddressList',
            success: (res) => {
              this.addressList = res.data
              this.addressList.forEach(item => {
                if (item.isDefault == true) {
                  this.addressId = item.addressId
                }
              })
            }
          })
        }
        this.deliveryModal = true
        this.deliveryForm.orderDeliveryId = row.orderDeliveryId
        this.deliveryForm.updateTime = row.updateTime
      }
    },
    handleCancelDelivery () {
      this.deliveryModal = false
      this.deliveryForm.isApproved = 1
      this.deliveryForm.remark = ''
      // this.addressList = []
    },
    handleDeliverySubmit () {
      // if (!this.deliveryForm.isApproved) {
      //   return this.$Message.warning('请选择审核结果！')
      // }
      if (!this.deliveryForm.remark) {
        return this.$Message.warning('请填写备注！')
      }
      if (this.deliveryState == 4) {
        this.deliveryForm.addressId = this.addressId
      }
      console.log('this.deliveryForm', this.deliveryForm)
      this.deliveryLoading = true
      let apiName = this.deliveryState === DeliveryStatus.UN_REFUND ? 'deliveryCheck' : 'deliveryCheckToBeSigned'
      this.api({
        apiName,
        postdata: this.deliveryForm,
        success: (res) => {
          this.handleCancelDelivery()
          this.$Notice.success({ title: '审核成功' })
          this.requestData()
        },
        complete: () => {
          this.deliveryLoading = false
        }
      })
    },
    handleShip (row) {
      return () => {
        // this.$Message.warning('该功能暂未开发哦！')
        // return
        this.orderDeliveryId = row.orderDeliveryId
        this.expressRow = row
        this.updateTime = row.updateTime
        this.shipModal = true
      }
    },
    handleCancelShip () {
      this.shipModal = false
      this.expressNo = ''
      this.expressType = ''
    },
    handleShipSubmit () {
      if (!this.expressNo) {
        return this.$Notice.warning({ title: '请填写快递单号！' })
      }
      if (!this.expressType) {
        return this.$Notice.warning({ title: '请选择物流渠道！' })
      }
      this.shipSubmitLoading = true
      let postdata = {
        orderDeliveryId: this.orderDeliveryId,
        expressNo: this.expressNo,
        updateTime: this.updateTime,
        expressType: this.expressType
      }
      this.api({
        apiName: 'pickUpGood',
        postdata,
        success: () => {
          this.requestData()
          this.expressRow.expressNo = this.expressNo
          this.expressRow.status = DeliveryStatus.UN_RECEIVE
          this.handleCancelShip()
          this.$Notice.success({ title: '已发货！' })
        },
        complete: () => {
          this.shipSubmitLoading = false
        }
      })
    },
    getExpressList () {
      this.api({
        apiName: 'getCompanyList',
        success: (res) => {
          this.expressCompanyList = res.data
        }
      })
    }
  },
  created () {
    if (!this.isBrand) {
      this.columns.splice(2, 0, {
        title: '品牌方',
        key: 'brandName',
        width: 150,
        align: 'center'
      })
    }
    this.getExpressList()
    this.requestData()
  }
}
</script>

<style lang="less">
.self-draw-table-con .search-con {
  padding: 10px 0;
  .search {
    &-col {
      display: inline-block;
      width: 150px;
      margin-right: 5px;
    }
    &-input {
      display: inline-block;
      width: 150px;
      margin-right: 5px;
    }
    &-date {
      margin-right: 5px;
    }
    &-btngroup {
      margin-right: 5px;
    }
  }
}
.vertical-center-modal {
  display: flex;
  align-items: center;
  justify-content: center;

  .ivu-modal {
    top: 0;
  }
  .modal-item {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
    .label {
      width: 100px;
      text-align: center;
    }
  }
}
</style>
