<template>
  <ai-list class="list" v-loading="isLoading" :element-loading-text="loadingText" element-loading-spinner="el-icon-loading">
    <ai-title
      slot="title"
      title="拒绝调价"
      isShowBottomBorder>
    </ai-title>
    <template slot="content">
      <div class="content">
        <ai-search-bar>
          <template #right>
            <el-button type="primary" @click="toLoad">加载</el-button>
            <el-button type="primary" @click="beforeRejct">拒绝调价</el-button>
          </template>
        </ai-search-bar>
        <ai-card title="数据明细" style="padding-bottom: 40px;">
          <ai-table
            :isShowPagination="false"
            :tableData="tableData"
            :col-configs="colConfigs"
            :total="tableData.length"
            height="700"
            style="margin-top: 8px;"
            @getList="() => {}">

            <el-table-column slot="productName" width="250px" :show-overflow-tooltip='true' label="商品名称"  fixed="left">
              <template slot-scope="scope">
                <div>
                  <el-image :src="scope.row.image" style="width: 40px; height: 40px" class="image" :preview-src-list="[scope.row.image]" />
                  {{ scope.row.productName }}
                </div>
              </template>
            </el-table-column>
          </ai-table>
        </ai-card>
      </div>
      <AiDialog
        title="拒绝原因"
        :visible.sync="rejectShow"
        :close-on-click-modal="false"
        customFooter
        height="500px"
        width="500px">
          <el-form :model="rejectForm" ref="rejectForm" class="form">
            <el-form-item
              prop="reason"
              label="拒绝原因："
              :rules="[{ required: true, message: '请输入拒绝原因', trigger: 'blur' }]">
              <el-input :rows="3" placeholder="请输入拒绝原因" type="textarea" v-model="rejectForm.reason"></el-input>
            </el-form-item>
          </el-form>
        
        <span slot="footer" class="dialog-footer">
          <el-button @click="rejectShow = false">关 闭</el-button>
          <el-button type="primary" @click="toReject">拒绝</el-button>
        </span>
      </AiDialog>
    </template>
  </ai-list>
</template>

<script>
import { Message } from 'element-ui'
import {sendChromeAPIMessage} from '@/api/chromeApi'
import {timestampToTime} from '@/utils/date'
import JsonExcel from 'vue-json-excel'

  export default {
    name: 'PriceDown',

    data () {
      return {
        reqData: {
          pageInfo: {
            pageSize: 100,
            pageNo: 1
          },
          status: 1
        },
        colConfigs: [
          { slot: 'productName', label: '商品名称', width: '250px', align: 'left', fixed: 'left' },
          { prop: 'mallName', label: '店铺来源', width: '250px', align: 'left', fixed: 'left' },
          { prop: 'priceOrderSn', label: '调价单号', width: '140px', align: 'left', fixed: 'left' },
          { prop: 'skcId', label: 'SKC ID', width: '120px', align: 'left' },
          { prop: 'skcExtCode', label: 'SKC货号', width: '100px', align: 'left' },
          { prop: 'priceBeforeExchange', label: '原申报价格', width: '100px', align: 'left' },
          { prop: 'newSupplyPrice', label: '调整后申报价格', width: '100px', align: 'left' },
          { prop: 'source', label: '申请来源', width: '120px', align: 'left' },
          { prop: 'adjustReason', label: '调价原因', align: 'left' }
        ],
        loadingText: '',
        isLoading: false,
        tableData: [],
        currentIndex: 0,
        rejectForm: {
          reason: ''
        },
        rejectShow: false
      }
    },
    components: {
      JsonExcel
    },
    created () {
    },
    methods: {
      beforeGetList() {
        this.$userCheck().then(() => {
          this.toLoad()
        }).catch((err) => {
          
        })
      },
      async toLoad() {
        if (this.$store.state.mallList.length == 0) {
          Message.error("请登录卖家中心，如已登录，请刷新助手")
          return
        }
        this.reqData.pageInfo.pageNo = this.startPage
        this.tableData = []
        this.currentIndex = 0
        this.isLoading = true
        for (let i = 0; i < this.$store.state.mallList.length; i++) {
          this.reqData.pageInfo.pageNo = 1
          this.loadingText = `正在加载店铺【${this.$store.state.mallList[i].mallName}】的调价信息`
          await this.load(this.$store.state.mallList[i])
        }
        this.isLoading = false
      },
      async load(mallObj) {
        let res = await sendChromeAPIMessage({
          url: 'marvel-mms/cn/api/kiana/magneto/price-adjust/page-query',
          needMallId: true,
          mallId: mallObj.mallId,
          anti: true,
          data: this.reqData})
        if (res.errorCode == 1000000 && res.result.total > 0) {
          for(let i = 0;i < res.result.list.length; i++) {
            let item = res.result.list[i];
            let data = {};
            data.id = item.id
            data.productName = item.productName
            data.image = item.image
            data.priceOrderSn = item.priceOrderSn
            data.skcId = item.skcId
            data.skcExtCode = item.skcExtCode
            data.source = item.source
            data.mallName = mallObj.mallName
            data.mallId = mallObj.mallId
            data.adjustReason = item.adjustReason
            data.newSupplyPrice = item.newSupplyPrice / 100
            data.num = item.skuInfoItemList.length
            let skus = []
            item.skuInfoItemList.map(item => {
              skus.push(item.productSkuId)
            })
            data.skus = skus.join(',')
            /*for(let k = 0; k < item.skuInfoItemList.length; k++) {
              data = {...data,
                productSkuId: item.skuInfoItemList[k].productSkuId,
                priceBeforeExchange: item.skuInfoItemList[k].priceBeforeExchange / 100,
                skuExtCode: item.skuInfoItemList[k].skuExtCode,
                spec: item.skuInfoItemList[k].spec
              }

              this.tableData.push(data)
            }*/
            this.tableData.push(data)

          }
          if (res.result.list.length == this.reqData.pageInfo.pageSize) {
            this.reqData.pageInfo.pageNo ++
            await this.load(mallObj)
          }
        }
      },
      beforeRejct() {
        if (this.tableData.length <= 0) {
          Message.error('请先加载待拒绝调价');
          return;
        }
        this.rejectShow = true
      },
      async toReject() {
        this.$refs.rejectForm.validate(async (valid) => {
          if (valid) {
            this.loadingText = '正在拼命处理中~'
            this.isLoading = true
            this.rejectShow = false
            await this.reject()
            this.isLoading = false
          }
        })
      },
      async reject() {
        let rejectIds = []
        for (let i = 0; i < this.tableData.length; i++) {
          rejectIds.push(this.tableData[i].id)
        }
        for (let j = 0; j < rejectIds.length; j++) {
          let obj = this.tableData.filter(item => {
            return item.id == rejectIds[j]
          })
          if (obj.length == 0) continue
          obj = this.tableData.filter(item => {
            return item.skus == obj[0].skus
          })
          let params = {}
          if (obj.length > 1) {
            params.adjustId = obj[0].id
            params.adjustResultMap = {}
            for (let k = 0; k < obj.length; k++) {
              params.adjustResultMap[obj[k].id] = 2
            }
            params.result = 2
          } else {
            params = {
              adjustId: obj[0].id,
              reason: this.rejectForm.reason,
              result: 2
            }
          }
          // console.log(obj[0].mallName, params)
          let res = await sendChromeAPIMessage({
          url: 'gmp/bg/magneto/api/price/purchase-adjust/review',
          needMallId: true,
          mallId: obj[0].mallId,
          anti: true,
          data: params})
          if (res.success) {
              this.removeByRejectId(obj)
            // this.remove(skuIds[j])
          }
          await this.$sleepSync(300)
        }
      },
      removeByRejectId(objArr) {
        for (let j = 0; j < objArr.length; j++) {
          for (let i = 0; i < this.tableData.length; i++) {
            if (this.tableData[i].id == objArr[j].id) {
              this.tableData.splice(i, 1)
              break
            }
          }
        }
      }
    }
  }
</script>

<style scoped lang="scss">
  .list {
    .title-right {
      display: flex;
      align-items: center;

      & > div:first-child {
        margin-right: 20px;
      }
    }
    ::v-deep.ai-list {
      .ai-list__content--right-wrapper {
        background: transparent;
        box-shadow: none;
        padding: 0!important;
      }
    }
  }
</style>