<template>
  <div class="order-list-con">
    <Card>
      <div class="search-con">
        <Input
          placeholder="订单编号"
          class="search-input"
          v-model="searchContent.oid"
          style="width: 200px"
          clearable
        />
        <Input
          placeholder="用户ID"
          class="search-input"
          v-model="searchContent.uid"
          style="width: 200px"
          clearable
        />
        <Select
          placeholder="订单状态"
          class="search-input"
          v-model="searchContent.orderState"
          style="width: 200px"
        >
          <Option value>全部</Option>
          <Option
            v-for="(item, index) of OrderState"
            :value="item"
            :key="'state-option-' + index"
            >{{ OrderStateObj[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"
        class="order-table-con"
        pagable
        v-model="tableData"
        :columns="columns"
        :currentPage="searchContent.pageNum"
        :pageSize="searchContent.pageSize"
        :totalSize="totalSize"
        :loading="loading"
        @on-change="handleCurrentChange"
      />
    </Card>

    <Modal
      v-model="refundModal"
      title="退款审核："
      :width="400"
      class-name="vertical-center-modal"
      @on-cancel="handleCancelRefund"
    >
      <Form
        ref="refundForm"
        :model="refundForm"
        :label-width="90"
      >
        <FormItem label="审核结果：" prop="isApproved">
          <RadioGroup v-model="refundForm.isApproved">
            <Radio :label="1">
              <span>通 过</span>
            </Radio>
            <Radio :label="0">
              <span>不通过</span>
            </Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="备注：">
          <Input
            placeholder="请输入..."
            v-model="refundForm.remark"
            type="textarea"
            :rows="6"
          />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button
          @click="handleRefundSubmit"
          :loading="refundLoading"
          type="primary"
          long
          >确 定</Button
        >
      </div>
    </Modal>
    <Modal
      v-model="editPriceModal"
      title="修改应付价格："
      :width="400"
      class-name="vertical-center-modal"
      @on-cancel="handleCancelEditPrice"
    >
      <Form
        ref="editPriceForm"
        :model="editPriceForm"
        :rules="editPriceRules"
        :label-width="90"
      >
        <FormItem label="优惠类型：" prop="consultDiscountType">
          <Select
            v-model="editPriceForm.consultDiscountType"
          >
            <Option
              value="1"
              key="1"
            >客户协商优惠
            </Option>
          </Select>
        </FormItem>
        <FormItem label="优惠金额：" prop="consultDiscountAmount">
          <Input
            placeholder=""
            v-model="editPriceForm.consultDiscountAmount"
            number
            type="number"
          >
            <span slot="append">元</span>
          </Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button
          @click="handleEditPriceSubmit"
          :loading="editPriceLoading"
          type="primary"
          long
        >确 定</Button
        >
      </div>
    </Modal>
  </div>
</template>

<script>
import Tables from '_c/tables'
import { formatTime } from '@/libs/tools'
import { OrderState, OrderStateObj } from '@/enums'
import OrderTableExpand from './order-table-expand'
import { apiVerify } from '../../api/apiVerify'
export default {
  inject: ['reload'],
  components: {
    Tables,
    OrderTableExpand
  },
  computed: {
    isBrand () {
      return this.$store.getters.isBrand
    }
  },
  data () {
    const validatePrice = (rule, value, callback) => {
      if (value < 0) {
        callback(new Error('请输入正确的价格！'))
      }
      if (!/^[0-9]+(.[0-9]{1,2})?$/.test(value)) {
        callback(new Error('最多精确至小数点后两位！'))
      }
      callback()
    }
    return {
      OrderState,
      OrderStateObj,
      searchContent: {
        oid: '',
        uid: '',
        orderState: '',
        goodsName: '',
        pageNum: 1,
        pageSize: 10
      },
      createTime: [],
      seriesList: [],
      columns: [
        { title: '订单编号', key: 'oid', minWidth: 180, align: 'left' },
        { title: '用户ID', key: 'uid', minWidth: 180, align: 'left' },
        { title: '产品编号',
          key: 'goodsIdList',
          minWidth: 180,
          align: 'left',
          render: (h, params) => {
            return h('div', params.row.goodsIdList.join(','))
          }
        },
        { title: '订单金额',
          key: 'total',
          width: 90,
          align: 'center',
          render: (h, params) => {
            return h('div', `￥${params.row.total}`)
          }
        },
        { title: '实付金额',
          key: 'amount',
          width: 90,
          align: 'center',
          render: (h, params) => {
            return h('div', `￥${params.row.amount}`)
          } },
        {
          title: '订单状态',
          key: 'orderState',
          align: 'center',
          width: 110,
          render: (h, params) => {
            let obj = OrderStateObj[params.row.orderState]
            return h(
              'Tag',
              {
                props: {
                  color: obj.color
                }
              },
              obj.label
            )
          }
        },
        { title: '备注',
          minWidth: 120,
          align: 'center',
          render: (h, params) => {
            return h('div', params.row.remark || '--')
          }
        },
        {
          title: '下单时间',
          align: 'center',
          width: 150,
          render: (h, params) => {
            return h('span', formatTime(params.row.createTime))
          }
        },
        {
          title: '操作',
          key: 'name',
          align: 'left',
          minWidth: 180,
          fixed: 'right',
          render: (h, params) => {
            let detailBtn = h(
              'Button',
              {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  margin: '5px'
                },
                on: {
                  click: this.handleDetail(params.row)
                }
              },
              '详 情'
            )
            let checkBtn = h(
              'Button',
              {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  display: params.row.orderState == OrderState.UN_REFUND ? 'inline-block' : 'none',
                  margin: '5px'
                },
                on: {
                  click: this.handleRefund(params.row)
                }
              },
              '审 核'
            )
            let editPriceBtn = h(
              'Button',
              {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  display: params.row.orderState == OrderState.PAYING ? 'inline-block' : 'none',
                  margin: '5px'
                },
                on: {
                  click: this.handleEditPrice(params.row)
                }
              },
              '修改价格'
            )
            return h('div', [detailBtn, editPriceBtn, checkBtn])
          }
        }
      ],
      tableData: [],
      totalSize: 0,
      loading: true,
      editPriceModal: false,
      editPriceForm: {
        consultDiscountType: 1,
        consultDiscountAmount: '',
        oid: '',
        updateTime: ''
      },
      editPriceRules: {
        consultDiscountAmount: [
          { required: true, type: 'number', message: '不能为空！', trigger: 'blur' },
          { validator: validatePrice, trigger: 'blur' }
        ],
        consultDiscountType: {
          required: true, message: '不能为空！', trigger: 'change'
        }
      },
      editPriceLoading: false,
      refundModal: false,
      refundForm: {
        oid: '',
        isApproved: 1,
        remark: ''
      },
      refundRules: {
        remark: {
          required: true, message: '不能为空！', trigger: 'blur'
        }
      },
      refundLoading: false
    }
  },
  methods: {
    requestData () {
      this.loading = true
      this.api({
        apiName: 'getOrderList',
        postdata: this.searchContent,
        complete: () => {
          this.loading = false
        },
        success: (res) => {
          this.tableData = res.data.records
          this.totalSize = res.data.total
        }
      })
    },
    handleSearch () {
      this.searchContent.pageNum = 1
      this.requestData()
    },
    handleRefresh () {
      this.reload()
    },
    handleCurrentChange (pageNum) {
      this.searchContent.pageNum = pageNum
      this.requestData()
    },
    handleRefund (row) { // 退款审核
      return () => {
        this.refundForm.oid = row.oid
        this.refundForm.updateTime = row.updateTime
        this.refundModal = true
      }
    },
    handleDetail (row) {
      return () => {
        let query = { oid: row.oid }
        this.$router.push({ name: 'order_detail', query })
      }
    },
    handleEditPrice (row) { // 修改价格
      return () => {
        this.editPriceForm.oid = row.oid
        this.editPriceForm.updateTime = row.updateTime
        this.editPriceModal = true
      }
    },
    handleEditPriceSubmit () {
      this.$refs.editPriceForm.validate((valid) => {
        if (valid) {
          this.editPriceLoading = true
          this.api({
            apiName: 'consultDiscount',
            postdata: this.editPriceForm,
            success: (res) => {
              this.handleCancelEditPrice()
              this.$Notice.success({ title: '修改成功！' })
              this.requestData()
            },
            complete: () => {
              this.editPriceLoading = false
            }
          })
        }
      })
    },
    handleCancelEditPrice () {
      this.editPriceModal = false
      this.$refs.editPriceForm.resetFields()
      this.editPriceForm.consultDiscountAmount = ''
      this.editPriceForm.consultDiscountType = ''
    },
    handleRefundSubmit () {
      console.log(this.refundForm.isApproved)
      // if (this.refundForm.isApproved == '') {
      //   return this.$Notice.warning({ title: '请选择审核结果！' })
      // }
      if (!this.refundForm.remark) {
        return this.$Notice.warning({ title: '请输入退款备注！' })
      }
      this.$refs.refundForm.validate((valid) => {
        if (valid) {
          this.refundLoading = true
          this.api({
            apiName: 'orderRefund',
            postdata: this.refundForm,
            success: (res) => {
              this.handleCancelRefund()
              this.$Notice.success({ title: '退货成功！' })
              this.requestData()
            },
            complete: () => {
              this.refundLoading = false
            }
          })
        }
      })
    },
    handleCancelRefund () {
      this.refundModal = false
      this.$refs.refundForm.resetFields()
      this.refundForm.remark = ''
      this.refundForm.isApproved = 1
    }
  },
  created () {
    if (!this.isBrand) {
      this.columns.splice(2, 0, {
        title: '品牌方',
        key: 'brandName',
        width: 150,
        align: 'center'
      })
    }
    this.requestData()
  }
}
</script>

<style lang="less">
.order-list-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;
    }
  }
}
.order-list-con .order-table-con {
  .ivu-table-expanded-cell {
    padding: 0 40px 10px 40px;
  }
}
.vertical-center-modal {
  display: flex;
  align-items: center;
  justify-content: center;

  .ivu-modal {
    top: 0;
  }
}
</style>
