<template>
  <div>
    <div style="display: flex; align-items: flex-end">
      <img
        src="@/assets/setting/user.png"
        alt
        style="width: 26px; height: 26px"
      >
      <span
        style="
          font-size: 18px;
          font-weight: bold;
          color: #333333;
          line-height: 26px;
          margin-left: 5px;
        "
      >{{ $t('postorder.header') }}</span>
    </div>
    <div style="display: flex; align-items: flex-end; margin-top: 5px">
      <div style="width: 75px; height: 4px; background: #396fff" />
      <div
        style="
          width: 75px;
          height: 1px;
          background: #fff;
          border: 1px solid #acacac;
        "
      />
    </div>
    <!-- 搜索工作栏 -->
    <el-form v-show="showSearch" ref="queryForm" :model="queryParams" size="small" :inline="true" style="margin-top: 20px;">
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item :label="$t('postorder.transport')" prop="transportId">
            <dict-selector v-model.number="queryParams.transportId" style="width: 160px;" :type="DICT_TYPE.ECW_TRANSPORT_TYPE" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('controlorder.No')" prop="searchKey">
            <el-input v-model="queryParams.searchKey" style="width: 230px;" :placeholder="$t('controlorder.NoRules')" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item :label="$t('postorder.marks')" prop="marks">
            <el-input v-model="queryParams.marks" style="width: 130px;" :placeholder="$t('controlorder.marksRules')" clearable />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item :label="$t('postorder.date')" prop="phone">
        <dict-selector v-model="dateFilterType" :type="DICT_TYPE.ECW_BEGINTIME_TYPE_ENDTIME" style="width: 150px; margin-right: 5px" />
        <el-date-picker v-model="dateFilter" type="datetimerange" range-separator="-" :start-placeholder="$t('postorder.start')" :end-placeholder="$t('postorder.end')" value-format="yyyy-MM-dd HH:mm:ss" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">{{ $t('common.search') }}</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">{{ $t('common.reload') }}</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <!-- 列表 -->
    <el-table
      :data="orderList"
      style="width: 100%"
    >
      <el-table-column
        type="index"
        width="50"
        align="center"
        header-align="center"
      />
      <el-table-column
        :label="$t('postorder.orderNo')"
        width="120"
        align="center"
        header-align="center"
      >
        <template slot-scope="scope">
          <router-link :to="{path: '/jiedao/jd-orderdetail',query: {orderId: scope.row.orderId}}" class="link-type">
            <span>{{ scope.row.orderNo }}</span>
          </router-link>
        </template>
      </el-table-column>
      <el-table-column
        prop="tidanNo"
        :label="$t('提单号')"
        width="100"
        align="center"
        header-align="center"
      />
      <el-table-column
        prop="transportId"
        :label="$t('postorder.transport')"
        width="100"
        align="center"
        header-align="center"
      >
        <template slot-scope="{row}">
          <dict-tag :type="DICT_TYPE.ECW_TRANSPORT_TYPE" :value="row.transportId" />
        </template>
      </el-table-column>
      <el-table-column
        prop="marks"
        :label="$t('postorder.marks')"
        width="100"
        align="center"
        header-align="center"
      />
      <el-table-column
        :label="$t('postorder.status')"
        prop="statusMsg"
        align="center"
        header-align="center"
      >
        <!-- <template slot-scope="scope">
          <dict-tag :type="DICT_TYPE.ORDER_STATUS" :value="scope.row.status" />
        </template> -->
      </el-table-column>
      <el-table-column
        prop="createTime"
        :label="$t('postorder.createTime')"
        align="center"
        header-align="center"
      />
      <el-table-column
        :label="$t('common.action')"
        align="center"
        class-name="small-padding fixed-width"
        width="150px"
        header-align="center"
      >
        <template slot-scope="scope">
          <el-button v-if="scope.row.status <= 2" size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row, false)">{{ $t('postorder.edit') }}</el-button>
          <el-button v-if="scope.row.status == 2" size="mini" type="text" icon="el-icon-delete" @click="oprateOrder(scope.row.orderId)">{{ $t('postorder.cancel') }}</el-button>
          <el-button v-if="scope.row.status == 5" size="mini" type="text" icon="el-icon-edit" @click="refundWarehouse(scope.row)">{{ $t('postorder.refundWarehouse') }}</el-button>
          <el-button v-if="scope.row.abnormalState>1&&scope.row.status!=88" size="mini" type="text" icon="el-icon-edit" @click="handleAbnormal(scope.row.orderId)">{{ $t('postorder.abnormal') }}</el-button>
          <el-button v-if="scope.row.status == 0" size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row.orderId)">{{ $t('postorder.delete') }}</el-button>
          <el-button v-if="scope.row.customsType == 2" size="mini" type="text" icon="el-icon-edit" @click.native="declarationOrderId=scope.row.orderId;declarationOrderNo=scope.row.orderNo">{{ $t('common.uploadDeclaration') }}</el-button>
          <el-button
            v-if="
              exclude(scope.row.status, [0]) &&
                exclude(scope.row.shipmentState, [320,322,323]) &&
                exclude(scope.row.abnormalState, [5,6,7,8])
            "
            size="mini"
            type="text"
            @click.native="printTagOrderId=scope.row.orderId"
          >{{ $t('打印标签') }}
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleCopy(scope.row)">{{ $t('postorder.copy') }}</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.rows"
      @pagination="getList"
    />
    <!-- 退仓弹窗 -->
    <el-dialog :title="$t('postorder.refundWarehouse')" :visible.sync="rwVisible" width="30%" append-to-body :close-on-click-modal="false">
      <el-form ref="rwForm" :model="rwForm" label-width="150px">
        <el-form-item
          :label="$t('postorder.refundOrderNo')"
        >
          <span>{{ rwForm.orderNo }}</span>
        </el-form-item>
        <el-form-item
          :label="$t('postorder.refundReason')"
          prop="reason"
        >
          <el-input v-model="rwForm.reason" type="textarea" :rows="4" :placeholder="$t('postorder.refundReasonNotice')" />
        </el-form-item>
        <el-form-item
          :label="$t('postorder.refundImg')"
          prop="imgUrl"
        >
          <el-upload
            class="upload-demo"
            action="#"
            :http-request="requestUpload"
            :before-upload="beforeUploadimg1"
            :file-list="fileList"
            multiple
            :limit="20"
            :on-exceed="moreFile"
            list-type="picture"
          >
            <el-button size="small" type="primary">{{ $t('realName.upload') }}</el-button>
            <div slot="tip" class="el-upload__tip">{{ $t('realName.uploadNotice') }}</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="rwSubmitForm">{{ $t('postorder.submitRefund') }}</el-button>
        <el-button @click="rwVisible=false;">{{ $t('postorder.noRefund') }}</el-button>
      </div>
    </el-dialog>
    <!-- 打印标签 -->
    <print-tag v-if="printTagOrderId !== null" :order-id="printTagOrderId" @close="printTagOrderId=null" />
    <declaration-documents v-if="declarationOrderId !== null" :order-id="declarationOrderId" :order-no="declarationOrderNo" @close="declarationOrderId=null" />
  </div>
</template>

<script>
import { getIssued, cancelOrder, deleteOrder, refundWarehouseApply, copyOrder } from '@/api/order'
import { parseTime } from '@/utils'
import RightToolbar from '@/components/RightToolbar'
import Pagination from '@/components/Pagination'
import DictTag from '@/components/DictTag'
import DictSelector from '@/components/DictSelector'
import PrintTag from './components/PrintTag'
import DeclarationDocuments from './components/DeclarationDocuments'
import { uploadFile } from '@/api/user'
export default {
  components: {
    RightToolbar,
    Pagination,
    DictTag,
    DictSelector,
    PrintTag,
    DeclarationDocuments
  },
  data() {
    return {
      parseTime,
      orderList: [],
      // 显示搜索条件
      showSearch: true,
      dateFilterType: '', // 日期筛选类别
      dateFilter: [], // 筛选日期
      printTagOrderId: null, // 显示打印标签的订单ID
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        page: 1,
        rows: 10
      },
      rwVisible: false,
      rwForm: {
      },
      fileList: [],
      imgUrl: [],
      declarationOrderId: null, // 显示报关资料订单ID
      declarationOrderNo: null // 显示报关资料订单ID
    }
  },
  computed: {
    // expoerCityList() {
    //   return this.tradeCityList.filter(item => item.type == 2)
    // },
    // importCityList() {
    //   return this.tradeCityList.filter(item => item.type == 1)
    // },
    combinedQueryParams() {
      const timeParams = {}
      if (this.dateFilterType && this.dateFilter) {
        timeParams['begin' + this.dateFilterType] = this.dateFilter[0]
        timeParams['end' + this.dateFilterType] = this.dateFilter[1]
      }
      return Object.assign({}, this.queryParams, timeParams)
    },
    exclude() {
      return (state, arr) => {
        return arr.indexOf(state) == -1
      }
    },
    isChinese() {
      return this.$i18n.locale === 'zh_CN'
    }
  },
  watch: {
    isChinese() {
      this.getList()
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      getIssued(this.combinedQueryParams).then((r) => {
        this.orderList = r.data.list
        this.total = r.data.total
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        page: 1,
        rows: 10
      }
      this.handleQuery()
    },
    /** 修改按钮操作 */
    handleUpdate(row, copy) {
      if (copy) {
        this.$router.push('jd-deliveryedit?id=' + row.orderId + '&copy=1')
      } else {
        this.$router.push('jd-deliveryedit?id=' + row.orderId)
      }
    },
    handleDelete(id) {
      this.$confirm(this.$t('是否确认删除订单')).then(function() {
        return deleteOrder(id)
      }).then(() => {
        this.getList()
        this.$message({
          message: this.$t('common.success'),
          type: 'success'
        })
      }).catch(() => {})
    },
    handleCopy(row){
      this.handleUpdate(row,  true )
      // copyOrder(row.orderId).then((res) => {
      //     this.handleUpdate({ orderId: res.data})
      // })
    },
    oprateOrder(orderId) {
      this.$confirm(this.$t('postorder.confirm'))
        .then(() => {
          cancelOrder(orderId).then(() => {
            this.getList()
          })
        })
    },
    refundWarehouse(row) {
      this.rwVisible = true
      this.rwForm = {
        orderId: row.orderId,
        orderNo: row.orderNo,
        reason: '',
        imgUrl: ''
      }
      this.imgUrl = []
      this.fileList = []
    },
    rwSubmitForm() {
      if (this.imgUrl.length > 0) {
        this.rwForm.imgUrl = this.imgUrl.join(',')
      }
      refundWarehouseApply(this.rwForm).then(() => {
        this.$message.success(this.$t('postorder.refundWarehouseSuccess'))
        this.getList()
        this.rwVisible = false
      })
    },
    handleAbnormal(id) {
      this.$router.push('jd-abnormal?id=' + id)
    },
    // 覆盖默认的上传行为
    requestUpload() {
    },
    // 上传预处理
    beforeUploadimg1(file) {
      let flag = false
      if (file.type.indexOf('image/') === -1) {
        this.$message.error(this.$t('setting.imgType'))
        flag = true
      } else {
        // 上传
        const formData = new FormData()
        formData.append('file', file)
        formData.append('path', this.uuid())
        uploadFile(formData).then(response => {
          // this.$set(this.rwForm, 'imgUrl', response.data)
          this.imgUrl.push(response.data)
        })
      }
      if (flag) return false
      console.log(this.imgUrl)
    },
    moreFile() {
      this.$message.error(this.$t('realName.uploadNotice'))
    },
    uuid() {
      var s = []
      var hexDigits = '0123456789abcdef'
      for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
      }
      s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
      s[8] = s[13] = s[18] = s[23] = '-'

      var uuid = s.join('')
      return uuid
    }
  }
}
</script>

<style scoped>
::v-deep .el-table__header .el-table__cell{
  background-color: #27417C;
  font-size: 13px;
  height: 48px;
  text-align: center;
  font-size: 13px;
  font-weight: 500;
  color: #FFFFFF;
}
</style>
