<template>
  <el-dialog
    custom-class="center-dialog"
    :title="title"
    top="0vh"
    :visible.sync="dialogFormVisible"
    width="70%"
    @close="close"
  >
    <el-scrollbar style="height: 600px">
      <div v-loading="loading">
        <div style="color: red; font-weight: 400; font-size: 18px">
          {{ data.return_state_name }}
        </div>
        <el-row :gutter="20">
          <el-col :offset="20" :span="6">
            <el-button
              v-if="data.return_state_id === 3105"
              class="el-icon-circle-close"
              @click="refusedOpen"
            >
              {{ __('不通过') }}
            </el-button>
            <el-button
              v-if="data.return_state_id === 3105"
              class="el-icon-circle-check"
              @click="reviewDialog = true"
            >
              {{ __('通过审核') }}
            </el-button>
            <el-button
              v-else-if="data.return_state_id === 3110"
              class="el-icon-circle-check"
              @click="receive"
            >
              {{ __('确认收货') }}
            </el-button>
            <el-button
              v-else-if="data.return_state_id === 3115"
              class="el-icon-circle-check"
              @click="refund"
            >
              {{ __('确认付款') }}
            </el-button>
          </el-col>
        </el-row>
        <div class="span_margin_right_10">
          <span>{{ __('退单号') }}：{{ data.return_id }}</span>
          <span>{{ __('订单号') }}：{{ data.order_id }}</span>
          <span>{{ __('客户名称') }}：{{ data.buyer_user_name }}</span>
          <span>{{ __('申请时间') }}：{{ data.return_add_time }}</span>
        </div>
        <el-table
          ref="returnTable"
          border
          :data="tableData"
          height="300"
          show-summary
          style="width: 98%; margin-top: 20px"
          :summary-method="getSummaries"
        >
          <el-table-column :label="__('商品名称')" prop="item_name" />
          <el-table-column :label="__('单位')" prop="unit_name" />
          <el-table-column :label="__('单价')" prop="order_item_unit_price" />
          <el-table-column :label="__('退款凭据')" prop="return_item_image">
            <template #default="{ row }">
              <div
                v-if="row.return_item_image && row.return_item_image.length > 0"
              >
                <el-image
                  v-for="(image, index) in row.return_item_image"
                  :key="index"
                  :preview-src-list="row.return_item_image"
                  preview-teleported
                  :src="image"
                  style="width: 35px; height: 35px"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column :label="__('数量')" prop="return_item_num" />
          <el-table-column
            :label="__('金额小计')"
            prop="return_item_subtotal"
          />
        </el-table>
        <el-row :gutter="20" style="margin-top: 10px">
          <el-col :offset="20" :span="6">
            <div>
              <span v-if="data.return_is_paid">
                &nbsp;&nbsp; {{ __('实际退款总额') }} ：
              </span>
              <span v-else-if="data.return_state_id !== 3125">
                <el-link type="primary" @click="showRefund">
                  {{ __('实际退款总额') }} ：
                </el-link>
              </span>
              <span v-text="data.return_refund_amount"></span>
              {{ __('元') }}
            </div>
          </el-col>
        </el-row>

        <div style="font-weight: 400; font-size: 18px; padding-top: 50px">
          {{ __('退货信息') }}
        </div>
        <el-divider />
        <div v-if="data.return_flag" class="span_margin_right_18">
          <span>{{ __('收货人') }}：{{ data.return_contact_name }}</span>
          <span>{{ __('联系方式') }}：{{ data.return_mobile }}</span>
          <span>{{ __('收货地址') }}：{{ data.return_addr }}</span>
          <!--      <span>{{__('退货类型')}}：{{ data.name }}</span>-->
          <span>{{ __('退货类型') }}：{{ __('退货退款') }}</span>
          <span>{{ __('商家备注') }}：{{ data.return_store_message }}</span>
        </div>
        <div v-else>
          <span>{{ __('仅退款') }}</span>
        </div>

        <div style="font-weight: 400; font-size: 18px; padding-top: 50px">
          {{ __('收货信息') }}
        </div>
        <el-divider />
        <div class="span_margin_right_18">
          <span>{{ __('收货人') }}：{{ data.da_name }}</span>
          <span>{{ __('联系方式') }}：{{ data.da_mobile }}</span>
          <span>{{ __('收货地址') }}：{{ getAddress }}</span>
        </div>

        <div style="font-weight: 400; font-size: 18px; padding-top: 50px">
          {{ __('退货详情') }}
        </div>
        <el-divider />
        <div class="span_margin_right_18">
          <span>{{ __('联系方式') }}：{{ data.return_tel }}</span>
          <span>{{ __('退货理由') }}：{{ data.return_buyer_message }}</span>
          <span>{{ __('退货物流名称') }}：{{ data.return_tracking_name }}</span>
          <span>
            {{ __('退货物流单号') }}：{{ data.return_tracking_number }}
          </span>
          <el-button
            v-if="viewLogisticsFlag"
            type="danger"
            @click="viewLogistics()"
          >
            查看物流
          </el-button>
        </div>
      </div>
    </el-scrollbar>
    <el-dialog
      append-to-body
      :title="refusedTitle"
      :visible.sync="refusedDialog"
      @close="refusedClose"
    >
      <el-form
        ref="refusedForm"
        v-loading="refusedLoading"
        label-position="left"
        label-width="100px"
        :model="refusedForm"
        :rules="refusedRules"
        size="medium"
      >
        <el-form-item :label="__('商家备注')" prop="return_store_message">
          <el-input
            v-model="refusedForm.return_store_message"
            clearable
            :placeholder="__('请输入单行文本商家备注')"
            :style="{ width: '100%' }"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="refusedClose">{{ __('取消') }}</el-button>
        <el-button type="primary" @click="refusedConfirm">
          {{ __('确定') }}
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      append-to-body
      :title="__('退货确认')"
      :visible.sync="reviewDialog"
      @close="reviewClose"
    >
      <el-form
        ref="reviewForm"
        v-loading="reviewLoading"
        label-position="left"
        label-width="100px"
        :model="reviewForm"
        :rules="reviewRules"
        size="medium"
      >
        <el-form-item :label="__('退货类型')" prop="return_flag">
          <el-radio-group v-model="reviewForm.return_flag" size="medium">
            <el-radio
              v-for="(item, index) in return_flagOptions"
              :key="index"
              :disabled="item.disabled"
              :label="item.value"
            >
              {{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          v-if="reviewForm.return_flag === 1"
          :label="__('请选择收货人')"
          :label-width="120"
          prop="receiving_address"
        >
          <el-select
            v-model="reviewForm.receiving_address"
            clearable
            :placeholder="__('请选择收货姓名')"
            :style="{ width: '30%' }"
          >
            <el-option
              v-for="item in addressList"
              :key="item.ss_id"
              :label="item.ss_name"
              :value="item.ss_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="__('商家备注')" prop="return_store_message">
          <el-input
            v-model="reviewForm.return_store_message"
            clearable
            :placeholder="__('请输入商家备注')"
            :style="{ width: '100%' }"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="reviewClose">{{ __('取消') }}</el-button>
        <el-button type="primary" @click="reviewConfirm">
          {{ __('确定') }}
        </el-button>
      </div>
    </el-dialog>
    <Refund ref="refund" @fetch-data="get" />
    <Returnlog ref="returnlog" @fetch-data="get" />
  </el-dialog>
</template>

<script>
import { translateTitle as __ } from '@/utils/i18n'
import { get, review, refused, receive, refund } from '@/api/order/return'
import { getAddressList } from '@/api/store/shipping/address'
import Refund from './RefundAmountEdit'
import Returnlog from './index'

export default {
  name: 'OrderReturnItem',
  components: { Refund, Returnlog },
  data() {
    return {
      reviewLoading: false,
      refusedLoading: false,
      addressList: [],
      viewLogisticsFlag: false,
      reviewForm: {
        return_flag: 0,
      },
      returnForm: {},
      reviewDialog: false,
      refusedForm: {},
      refusedDialog: false,
      loading: false,
      tableData: [],
      data: {},
      rules: {},
      return_id: '',
      dialogFormVisible: false,
      title: '',
      refusedTitle: '',
      refusedRules: {
        return_store_message: [
          {
            required: true,
            message: '请输入单行文本商家备注',
            trigger: 'blur',
          },
        ],
      },
      reviewRules: {
        return_flag: [
          {
            required: true,
            message: '退货类型不能为空',
            trigger: 'change',
          },
        ],
        return_store_message: [
          {
            required: true,
            message: '请输入商家备注',
            trigger: 'blur',
          },
        ],
        receiving_address: [
          {
            required: true,
            message: '请选择收货人',
            trigger: 'blur',
          },
        ],
      },
      return_flagOptions: [
        {
          label: '不用退货',
          value: 0,
        },
        {
          label: '需要退货',
          value: 1,
        },
      ],
    }
  },
  computed: {
    getAddress() {
      let address = ''
      const da_province = this.data.da_province
      const da_city = this.data.da_city
      const da_county = this.data.da_county
      const da_address = this.data.da_address
      if (da_province) {
        address += da_province
      }
      if (da_city) {
        address += '/' + da_county
      }
      if (da_county) {
        address += '/' + da_county
      }
      if (da_address) {
        address += ' ' + da_address
      }
      return address
    },
  },
  updated() {
    this.$nextTick(() => {
      this.$refs['returnTable'].doLayout()
    })
  },
  created() {
    this.getAddressList()
  },
  methods: {
    showRefund() {
      let return_id = this.data.return_id
      let return_refund_amount = this.data.return_refund_amount
      this.$refs['refund'].showEdit(return_id, return_refund_amount)
    },
    // 统计申请总额
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      sums[0] = '申请总额'
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '申请总额'
          return
        }
        if (index === 4 || index === 5) {
          let values = 0
          if (index === 4) {
            values = data.map((item) => {
              return Number(item['return_item_num'])
            })
          }
          if (index === 5) {
            values = data.map((item) => {
              return Number(item['return_item_subtotal'])
            })
          }
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return prev + curr
            } else {
              return prev
            }
          }, 0)
        }
      })
      return sums
    },
    async viewLogistics() {
      this.returnForm.return_tracking_name = this.data.return_tracking_name
      this.returnForm.return_tracking_number = this.data.return_tracking_number
      this.$refs['returnlog'].showEdit(this.returnForm)
    },
    async showEdit(row) {
      this.dialogFormVisible = true
      this.return_id = row.return_id
      await this.get(row.return_id)
    },
    close() {
      this.return_id = ''
      this.dialogFormVisible = false
    },
    async get(return_id) {
      if (!return_id) {
        return_id = this.return_id
      }
      this.loading = true
      const { data } = await get({ return_id: return_id })
      this.tableData = data.items
      this.data = Object.assign({}, data)
      if (this.data.return_tracking_number) {
        this.viewLogisticsFlag = true
      }
      this.loading = false
    },
    reviewConfirm() {
      this.$refs['reviewForm'].validate(async (valid) => {
        this.reviewLoading = true
        if (valid) {
          this.reviewForm.return_id = this.return_id
          const { msg, status } = await review(this.reviewForm)
          if (200 == status) {
            this.$baseMessage(msg, 'success')
          } else {
            this.$baseMessage(msg, 'error')
          }
          this.reviewClose()
          await this.get(this.return_id)
          this.reviewLoading = false
        } else {
          this.reviewLoading = false
          return false
        }
      })
    },
    refusedConfirm() {
      this.$refs['refusedForm'].validate(async (valid) => {
        this.refusedLoading = true
        if (valid) {
          this.refusedForm.return_id = this.return_id
          const { msg, status } = await refused(this.refusedForm)
          if (200 == status) {
            this.$baseMessage(msg, 'success')
          } else {
            this.$baseMessage(msg, 'error')
          }
          this.refusedClose()
          await this.get(this.return_id)
          this.refusedLoading = false
        } else {
          this.refusedLoading = false
          return false
        }
      })
    },
    reviewClose() {
      this.reviewDialog = false
      this.$refs['reviewForm'].resetFields()
      this.reviewForm = {
        return_flag: 0,
      }
    },
    refusedClose() {
      this.refusedDialog = false
      this.$refs['refusedForm'].resetFields()
      this.refusedForm = {}
    },
    refusedOpen() {
      this.refusedTitle = this.return_id + ' 不通过审核'
      this.refusedDialog = true
    },
    reviewOpen() {
      // 默认地址
      this.setDefaultAddress()
      this.reviewDialog = true
    },
    setDefaultAddress() {
      let addressList = this.addressList
      if (addressList || addressList.length === 0) return
      let address = addressList.find((item) => item.ss_is_default === 1)
      if (address) {
        this.reviewForm.receiving_address = address.ss_id
      }
    },
    async getAddressList() {
      const { data } = await getAddressList()
      if (data && data.length > 0) {
        this.addressList = data
      }
    },
    async receive() {
      const { msg, status } = await receive({ return_id: this.return_id })
      await this.get(this.return_id)
      if (200 == status) {
        this.$baseMessage(msg, 'success')
      } else {
        this.$baseMessage(msg, 'error')
      }
    },
    async refund() {
      const { msg, status } = await refund({ return_id: this.return_id })
      await this.get(this.return_id)
      if (200 == status) {
        this.$baseMessage(msg, 'success')
      } else {
        this.$baseMessage(msg, 'error')
      }
    },
  },
}
</script>
<style>
.span_margin_right_18 span {
  margin-right: 18px;
}

.span_margin_right_10 span {
  margin-right: 10px;
}
</style>
