<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.uname"
        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 && deliveryTime != 0 ">
        <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>
    <Modal
      v-model="isGoods"
      title="商品信息"
      :width="600"
      class-name="vertical-center-modal"
      @on-cancel="handelCancelGoods"
      footer-hide
    >
      <div class="goods-info">
        <tables :columns="goodsColumns" v-model="goodsList">
        </tables>
      </div>
    </Modal>
    <Modal
      v-model="isuserInfo"
      title="收件人信息"
      :width="500"
      class-name="vertical-center-modal"
      footer-hide
      @on-cancel="handelCancelUser"
    >
      <div class="user-info">
        <div>
          <label>收件人：</label>
          <span>{{uname}}</span>
        </div>
        <div>
          <label>手机号：</label>
          <span>{{uphone}}</span>
        </div>
        <div>
          <label>收件地址：</label>
          <span>{{uaddress}}</span>
        </div>
      </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
    },
    platform () {
      return this.$store.state.admin.type == 1 || this.$store.state.admin.type == 4
    }
  },
  data () {
    return {
      DeliveryType,
      DeliveryTypeName,
      DeliveryStatus,
      DeliveryStatusObj,
      searchContent: {
        deliveryState: '',
        gid: '',
        uid: '',
        uname: '',
        orderDeliveryId: '',
        pageNum: 1,
        pageSize: 10
      },
      deliveryTime: '',
      createTime: [],
      goodsColumns: [
        { title: '商品',
          key: 'goods',
          minWidth: 200,
          align: 'center',
          render: (h, params) => {
            let { name, propValList, thumb } = params.row
            let renderData = []
            renderData.push(
              h('div', {
                style: {
                  display: 'flex',
                  alignItems: 'center',
                  height: '70px'
                }
              },
              [
                h('img', {
                  attrs: {
                    src: thumb,
                    alt: name
                  },
                  style: {
                    width: '70px',
                    height: '50px',
                    display: thumb ? 'inline-block' : 'none'
                  }
                }),
                h('div',
                  {
                    style: {
                      textAlign: 'left',
                      marginLeft: '8px'
                    }
                  },
                  [
                    h('span', {
                      style: {
                        display: 'block',
                        fontSize: '16px',
                        fontWeight: 'bold'
                      }
                    }, '商品名称：' + name),
                    h('span', {
                      style: {
                        display: 'block'
                      }
                    }, '规格：' + propValList.join(','))
                  ])
              ])
            )
            return renderData
          }
        },
        { title: '数量', key: 'number', minWidth: 120, align: 'center' }
      ],
      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: '收件人',
          width: 100,
          key: 'uname',
          align: 'center',
          // render: (h, params) => {
          //   return h('Tooltip', {
          //     props: { placement: 'top' }
          //   }, [
          //     params.row.phone,
          //     h('span', {
          //       slot: 'content',
          //       style: {
          //         whiteSpace: 'normal',
          //         wordBreak: 'break-all'
          //       }
          //     }, params.row.phone)
          //   ])
          // }
          render: (h, params) => {
            return h(
              'Button',
              {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: this.handleUserDetail(params.row)
                }
              },
              // '查看'
              params.row.uname
            )
          }
        },
        { title: '商品件数',
          key: 'number',
          width: 90,
          align: 'center'
        },
        { title: '商品信息',
          width: 90,
          align: 'center',
          render: (h, params) => {
            return h(
              'Button',
              {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '5px'
                },
                on: {
                  click: this.handleGoodsDetail(params.row)
                }
              },
              '查看'
            )
          }
        },
        { 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', [!this.platform && 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: [],
      isGoods: false,
      goodsList: [],
      isuserInfo: false,
      uname: '',
      uphone: '',
      uaddress: ''
    }
  },
  methods: {
    requestData () {
      this.loading = true
      this.searchContent.orderDeliveryId = this.searchContent.orderDeliveryId.replace(/\s+/g, '')
      this.searchContent.uid = this.searchContent.uid.replace(/\s+/g, '')
      this.searchContent.gid = this.searchContent.gid.replace(/\s+/g, '')
      this.searchContent.uname = this.searchContent.uname.replace(/\s+/g, '')
      console.log("SEARCH: " + this.searchContent.uname)
      this.api({
        apiName: 'getPickUpList',
        postdata: this.searchContent,
        success: (res) => {
          this.totalSize = res.data.total
          this.tableData = res.data.records
        },
        complete: () => {
          this.loading = false
        }
      })
    },
    handleGoodsDetail (row) {
      return () => {
        this.isGoods = true
        // console.log('row', row)
        this.goodsList = row.goodsList
      }
    },
    handleUserDetail (row) {
      return () => {
        this.isuserInfo = true
        // console.log('row', row)
        this.uname = row.uname
        this.uphone = row.phone
        this.uaddress = row.address
      }
    },
    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
        this.deliveryTime = row.deliveryTime
        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 = ''
    },
    handelCancelGoods () {
      this.isGoods = false
    },
    handelCancelUser () {
      this.isuserInfo = false
      this.uname = ''
      this.uphone = ''
      this.uaddress = ''
    },
    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>
