<template>
  <div class="app-container">
    <div v-loading.fullscreen.lock="loadingFull" />
    <el-tabs v-model="searchParams.type" @tab-click="handleClick">
      <el-tab-pane label="工作室" name="1" />
      <el-tab-pane label="优享店" name="2" />
      <el-tab-pane label="体验店" name="3" />
    </el-tabs>
    <div>
      <el-form ref="searchForm" inline :model="searchParams" :rules="searchRules">
        <el-form-item>
          <el-input v-model="searchParams.search_name" placeholder="请输入门店名称" size="small" style="width:250px" />
        </el-form-item>
        <el-form-item prop="time">
          <el-date-picker
            v-model="searchParams.time"
            type="month"
            placeholder="选择结算月份"
            size="small"
            value-format="yyyy-MM"
          />
        </el-form-item>
        <el-form-item>
          <el-select v-model="awardType" placeholder="请选择奖励方式" size="small" :disabled="searchParams.type !== '2'">
            <el-option label="奖励物" value="0" />
            <el-option label="奖励钱" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            size="small"
            @click="handleSearch"
          >
            查询
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 奖励物 -->
    <div v-if="!toggleFlag">
      <el-table
        ref="multipleTable"
        :data="table"
        :header-cell-style="{ background: '#f8fbfc' }"
        class="tableBorder"
        border
        stripe
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column
          prop="storename"
          label="门店名称"
          align="center"
        />
        <el-table-column
          prop="nickname"
          label="主管销售昵称"
          align="center"
        >
          <template slot-scope="{ row }">
            {{ row.nickname }}
          </template>
        </el-table-column>
        <el-table-column
          prop="account"
          label="总消费"
          align="center"
        >
          <template slot-scope="{ row }">
            {{ `￥${row.account}` }}
          </template>
        </el-table-column>
        <el-table-column
          prop="rewards"
          label="待结算"
          align="center"
        >
          <template slot-scope="{ row }">
            {{ `￥${row.rewards}` }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="150"
        >
          <template slot-scope="{ row }">
            <el-button type="text" @click="handleAwardGood(row)">结算</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="batch-container">
        <!-- 分页 -->
        <pagination
          :total="tableTotal"
          :limit="searchParams.page_size"
          :page="searchParams.page_index"
          style="margin-top:0"
          @pagination="changePagination"
          @update:limit="changePagination"
        />
      </div>
    </div>
    <!-- 奖励钱 -->
    <div v-if="toggleFlag">
      <el-table
        ref="multipleTable2"
        :data="table"
        class="tableBorder"
        :header-cell-style="{background: '#f8fbfc'}"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column
          prop="name"
          label="门店名称"
          align="center"
        />
        <el-table-column
          prop="user"
          label="主管代理昵称"
          align="center"
        >
          <template slot-scope="{ row }">
            {{ row.user && row.user.nickname }}
          </template>
        </el-table-column>
        <el-table-column
          prop="info"
          label="进货详情"
          align="center"
        >
          <template slot-scope="{ row }">
            <p v-for="(item, i) in row.info" :key="i" style="line-height: 23px">{{ `${changeType(item.type)}: ${item.total }件` }}</p>
          </template>
        </el-table-column>
        <el-table-column
          prop="info"
          label="奖励价格"
          align="center"
        >
          <template slot-scope="{ row }">
            <p v-for="(item, i) in row.info" :key="i" style="line-height: 23px">{{ `${changeType(item.type)}: ${item.price}元/件` }}</p>
          </template>
        </el-table-column>
        <el-table-column
          prop="info"
          label="奖励合计"
          align="center"
        >
          <template slot-scope="{ row }">
            <p v-for="(item, i) in row.info" :key="i" style="line-height: 23px">{{ `${changeType(item.type)}: ￥${item.totalprice}` }}</p>
          </template>
        </el-table-column>
        <el-table-column
          prop="info"
          label="总奖励"
          align="center"
        >
          <template slot-scope="{ row }">
            ￥{{ changeAllPrice(row.info, 'totalprice') }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="150"
        >
          <template slot-scope="{ row }">
            <el-button type="text" @click="handleAwardMoney(row)">结算</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="table-control">
        <el-button type="primary" size="mini" @click="handleAwardMoneyMany">批量结算</el-button>
        <div class="batch-container">
          <!-- 分页 -->
          <pagination
            :total="tableTotal"
            :limit="searchParams.page_size"
            :page="searchParams.page_index"
            style="margin-top:0"
            @pagination="changePagination"
            @update:limit="changePagination"
          />
        </div>
      </div>
    </div>
    <!-- 结算物 -->
    <el-dialog
      title="结算奖励-物"
      :visible.sync="visible.goods"
      :before-close="handleCloseAward"
    >
      <el-form label-width="130px">
        <el-form-item label="奖励门店:">{{ awardInfo.name }}</el-form-item>
        <el-form-item label="奖励金额:">￥{{ awardInfo.price }}</el-form-item>
        <el-form-item label="选择奖励商品:">
          <el-radio
            v-for="item in goodsList"
            :key="item.id"
            v-model="awardGoodsId"
            :value="item.id"
            :label="item.id"
            size="small"
            border
            style="margin-top:10px"
            @change="handleComputedNum(item.tjprice)"
          >
            {{ `${item.name}-￥${item.tjprice}` }}
          </el-radio>
        </el-form-item>
        <el-form-item label="商品数量:">{{ awardGoodsNum }}</el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="handleSureAwardGood">确定</el-button>
          <el-button size="small" @click="handleCloseAward">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
// api
import { getShopSaleList, getShopSaleListMoney, setAwardMoney, setAwardGood, getRewardGoodList } from '@/api/finance/shopSaleAward'
export default {
  data() {
    return {
      searchParams: {
        page_index: 1,
        page_size: 10,
        search_name: '',
        time: `${new Date().getFullYear()}-${new Date().getMonth()}`,
        type: '2'
      },
      table: [],
      tableTotal: 0,
      searchRules: {
        time: [
          { required: true, message: '请选择查询月份', trigger: 'change' }
        ]
      },
      awardType: '0',
      toggleFlag: false,
      visible: {
        goods: false
      },
      awardInfo: {
        name: '',
        price: '',
        id: ''
      },
      goodsList: [],
      awardGoodsId: '',
      awardGoodsNum: 0,
      awardGoodsPrice: '',
      loadingFull: false
    }
  },
  watch: {
    'awardType': function() {
      const { type } = this.searchParams
      let out
      switch (type) {
        case '1':
          out = '0'
          break
        case '3':
          out = '1'
          break
        default:
          out = '0'
      }
      return out
    }
  },
  created() {
    this.init()
    this.getRewardGoodList()
  },
  methods: {
    // 初始化
    init() {
      const { type } = this.searchParams
      switch (type) {
        case '1':
          this.getShopSaleList()
          break
        case '3':
          this.getShopSaleListMoney()
          break
        default:
          switch (this.awardType) {
            case '0':
              this.getShopSaleList()
              break
            case '1':
              this.getShopSaleListMoney()
          }
      }
    },
    // 奖励物接口 - 1工作室 2优享店
    async getShopSaleList() {
      this.loadingFull = true
      try {
        const res = await getShopSaleList(this.searchParams)
        const { code, message } = res
        if (code === 200) {
          const { data } = res
          const { list, total } = data
          this.table = list
          this.tableTotal = total
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        this.$message.error('获取门店奖励失败')
      }
      this.loadingFull = false
    },
    // 奖励钱接口 - 3体验店 2优享店
    async getShopSaleListMoney() {
      this.loadingFull = true
      try {
        const res = await getShopSaleListMoney(this.searchParams)
        const { code, message } = res
        if (code === 200) {
          const { data } = res
          const { list, total } = data
          this.table = list
          this.tableTotal = total
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        this.$message.error('获取门店奖励失败')
      }
      this.loadingFull = false
    },
    // 查询搜索
    handleSearch() {
      this.$refs.searchForm.validate((valid) => {
        if (valid) {
          if ((this.searchParams.type === '2' && this.awardType === '1') || this.searchParams.type === '3') {
            this.toggleFlag = true
          } else {
            this.toggleFlag = false
          }
          this.searchParams.page_index = 1
          this.init()
        } else {
          return false
        }
      })
    },
    // tab切换
    handleClick(tab, event) {
      this.searchParams.type = tab.name
      if (tab.name === '1') {
        this.awardType = '0'
        this.toggleFlag = false
      } else if (tab.name === '2') {
        if (this.awardType === '0') {
          this.toggleFlag = false
        } else {
          this.toggleFlag = true
        }
      } else {
        this.awardType = '1'
        this.toggleFlag = true
      }
      this.init()
    },
    // 显示类型
    changeType(type) {
      let out
      switch (type) {
        case 1:
          out = '精装版'
          break
        case 2:
          out = '简约版'
          break
        case 3:
          out = '老人版'
          break
        default:
          out = ''
      }
      return out
    },
    // 结算 钱
    async setAwardMoney(data) {
      try {
        const res = await setAwardMoney(data)
        const { code, message } = res
        if (code === 200) {
          this.$message.success(message)
          this.init()
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        this.$message.error('结算门店(钱)失败!!')
      }
    },
    // 结算钱
    handleAwardMoney(row) {
      const { id, name } = row
      this.$confirm(`是否为门店: ${name}结算${this.searchParams.time}奖励(钱)`, '业绩奖励-钱', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.setAwardMoney({
          type: this.searchParams.type,
          time: this.searchParams.time,
          storeids: [id]
        })
      })
    },
    // 批量结算-钱
    handleAwardMoneyMany() {
      const stores = this.$refs.multipleTable2.selection
      if (stores.length < 1) {
        this.$message.warning('请先选择门店!!')
        return false
      }
      const ids = []
      stores.map(item => {
        ids.push(item.id)
      })
      this.$confirm(`确认为选择门店结算${this.searchParams.time}奖励(钱)`, '奖励结算-钱', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.setAwardMoney({
          storeids: ids,
          type: this.searchParams.type,
          time: this.searchParams.time
        })
      })
    },
    // 结算-货
    async setAwardGood(data) {
      try {
        const res = await setAwardGood(data)
        const { code, message } = res
        if (code === 200) {
          this.handleCloseAward()
          this.init()
          this.$message.success(message)
        } else {
          this.$message.error(message)
        }
      } catch (e) {
        this.$message.error('结算门店(货)失败!!')
      }
    },
    // 获取结算奖励商品
    async getRewardGoodList() {
      try {
        const res = await getRewardGoodList()
        // const { code, message } = res
        if (res) {
          const { data } = res
          this.goodsList = data
        }
      } catch (e) {
        this.$message.error('获取结算奖励商品失败!!')
      }
    },
    // 结算-货
    handleAwardGood(row) {
      const { storename, rewards, id } = row
      this.awardInfo.name = storename
      this.awardInfo.price = rewards
      this.awardInfo.id = id
      this.visible.goods = true
    },
    // 确认结算-货
    handleSureAwardGood() {
      if (!this.awardGoodsId) {
        this.$message.error('请选择结算的商品!!')
        return false
      }
      this.setAwardGood({
        type: this.searchParams.type,
        time: this.searchParams.time,
        storeids: [this.awardInfo.id],
        goods_id: this.awardGoodsId,
        goods_price: this.awardGoodsPrice,
        goods_num: this.awardGoodsNum
      })
    },
    // 计算数量
    handleComputedNum(price) {
      this.awardGoodsNum = Math.floor(Number(this.awardInfo.price) / Number(price))
      this.awardGoodsPrice = price
    },
    // 关闭弹窗
    handleCloseAward() {
      this.awardInfo.name = ''
      this.awardInfo.price = ''
      this.awardGoodsNum = ''
      this.awardInfo.id = ''
      this.awardGoodsId = ''
      this.awardGoodsNum = 0
      this.awardGoodsPrice = ''
      this.visible.goods = false
    },
    // 显示所有金额
    changeAllPrice(arr, key) {
      if (!arr) {
        return 0
      }
      if (!(arr instanceof Array)) {
        return 0
      }
      let num = 0
      arr.map((item) => {
        num += item[key]
      })
      return num
    },
    // 分页页码变化
    changePagination(data) {
      const { page, limit } = data
      this.searchParams.page_size = limit
      this.searchParams.page_index = page
      this.init()
    }
  }
}
</script>
