<template>
  <div class="app-container coupon-add">
    <br>
    <el-row :gutter="10">
      <el-col  :xs="{span: 22, offset: 0}" :sm=" {span: 18, offset: 0}" :lg="{span: 10, offset: 0}">
        <el-form ref="addItem" :model="addData" :rules="rules" label-width="160px">
          <el-form-item label="券名称:" prop="title">
            <el-input v-model="addData.title" :readonly="readonly" placeholder="请输入券名称" :maxlength="32" show-word-limit />
          </el-form-item>
          <el-form-item label="使用场景:" prop="type">
            <el-radio-group v-model="addData.type" :disabled="readonly || addData.status === 'on' || addData.status === 'off'">
              <el-radio :label="2">门店消费</el-radio>
              <el-radio :label="1">盲票购买</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="券金额:" prop="discount">
            <el-input v-model.number="addData.discount" :readonly="readonly" type="number" :min="0" placeholder="请输入券券金额">
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
          <!-- <el-form-item label="数量:" prop="quantity">
            <el-input v-model.number="addData.quantity" type="number" :min="0" placeholder="请输入券数量">
              <template slot="append">元</template>
            </el-input>
          </el-form-item> -->
          <!-- <el-form-item label="图片:" prop="picUrl">
            <Upload :value="addData.picUrl ? [{ fileName: addData.picUrl }] : []" @input="addData.picUrl = $event[0] ? $event[0].fileName : ''" :limit="1" />
          </el-form-item> -->
          <el-form-item v-if="addData.type === 2" label="门店默认承担比例:" prop="channelSharedRate">
            <el-input v-model="addData.channelSharedRate" :readonly="readonly" type="number" placeholder="请输入门店默认承担比例">
              <template slot="append">%</template>
            </el-input>
            <div class="tip">若门店承担100%，则核销后公司不需要打款给门店，依此类推。</div>
          </el-form-item>
          <el-form-item label="最低消费金额:" prop="minOrderAmt">
            <el-input v-model="addData.minOrderAmt" :readonly="readonly" type="number" placeholder="请输入可使用的最低消费金额">
              <template slot="append">元</template>
            </el-input>
            <div class="tip">最低消费金额为0则为无门槛优惠券</div>
          </el-form-item>
          <el-form-item label="有效期限:" prop="dueDays">
            <el-select v-model="addData.dueDays" clearable placeholder="请选择有效期限" :disabled="readonly">
              <el-option label="30天" :value="30"></el-option>
              <el-option label="60天" :value="60"></el-option>
              <el-option label="90天" :value="90"></el-option>
              <el-option label="180天" :value="180"></el-option>
            </el-select>
            <!-- <el-input v-model.number="addData.dueDays" :readonly="readonly" placeholder="请输入有效期限">
              <template slot="prepend">领取之日起</template>
              <template slot="append">天有效</template>
            </el-input> -->
          </el-form-item>
          <el-form-item label="使用说明:" prop="description">
            <el-input type="textarea" rows="4" :readonly="readonly" v-model="addData.description" placeholder="请输入使用说明 对用户可见"/>
          </el-form-item>
          <el-form-item v-if="addData.type === 2" label="使用范围:" prop="useArea">
            <el-radio-group v-model="addData.useArea" :disabled="readonly || addData.status === 'on' || addData.status === 'off'">
              <el-radio :label="2">进票门店</el-radio>
              <el-radio :label="1">指定门店</el-radio>
              <el-radio :label="0">所有门店</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-else label="使用范围:" prop="useArea">
            <el-radio-group v-model="addData.useArea" :disabled="readonly || addData.status === 'on' || addData.status === 'off'">
              <el-radio :label="0">所有盲票</el-radio>
              <el-radio :label="3">线上盲票</el-radio>
              <el-radio :label="4">线下盲票</el-radio>
              <el-radio :label="1">指定盲票</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
    <el-row :gutter="18">
     <el-col :span="18" :offset="2">
       <div v-if="addData.useArea === 1 && addData.type === 1" style="padding: 0 20px">
         <el-table :data="addData.ticketBoxList" height="300px">
           <el-table-column label="盲票ID" prop="boxId" min-width="90" />
           <el-table-column label="盲票图片" prop="picUrl" align="center">
             <template slot-scope="{row}">
               <a target="_black" v-if="row.picUrl && row.picUrl.split(',').length > 0" :href="`${IMG_URL + row.picUrl}`"><img :src="`${IMG_URL + row.picUrl.split(',')[0]}`" style="max-height: 37px;max-width: 54px"></a>
               <span v-else>-</span>
             </template>
           </el-table-column>
           <el-table-column label="盲票名称" prop="title" />
           <el-table-column label="盲票面值" prop="facePrice" >
             <template slot-scope="{row}">
               ¥{{$numberFormat(row.facePrice)}}
             </template>
           </el-table-column>
           <el-table-column label="盲票类型" prop="type">
             <template slot-scope="{row}">
               {{ row.type && JSON.parse(row.type).desc }}
             </template>
           </el-table-column>
           <el-table-column label="盲票状态" prop="status">
             <template slot-scope="{row}">
               <el-tag :type="row.status && JSON.parse(row.status).value === 'on' ? 'success' : 'info'">{{ row.status && JSON.parse(row.status).desc }}</el-tag>
             </template>
           </el-table-column>
           <el-table-column v-if="!readonly" prop="date" label="操作">
             <template slot-scope="{ $index }">
               <el-button type="text" class="del" @click="addData.ticketBoxList.splice($index, 1)">删除</el-button>
             </template>
           </el-table-column>
         </el-table>
         <br>
         <el-button v-if="!readonly" type="primary" size="small" plain @click="funSelectShow">选择盲票</el-button> <span style="margin-left: 10px">已选盲票（{{ addData.ticketBoxList.length }}）</span>
       </div>
       <div v-if="addData.useArea === 1 && addData.type === 2" style="padding: 0 20px">
         <el-table :data="channelList" height="300px">
           <el-table-column label="门店编号" prop="channelId" min-width="90" />
           <el-table-column label="门店名称" prop="name" />
           <el-table-column label="手机号码" prop="mobile" />
           <el-table-column label="上级渠道" prop="parentsName"/>
           <el-table-column label="认证状态" prop="status">
             <template slot-scope="{row}">
               <el-tag :type="row.certifyStatus && JSON.parse(row.certifyStatus).value === 'y' ? 'success' : 'info'">{{ row.certifyStatus && JSON.parse(row.certifyStatus).desc }}</el-tag>
             </template>
           </el-table-column>
           <el-table-column v-if="!readonly" prop="date" label="操作">
             <template slot-scope="{ $index }">
               <el-button type="text" class="del" @click="channelList.splice($index, 1)">删除</el-button>
             </template>
           </el-table-column>
         </el-table>
         <br>
         <el-button v-if="!readonly" type="primary" size="small" plain @click="funChannelShow">选择门店</el-button> <span style="margin-left: 10px">已选门店（{{ channelList.length }}）</span>
       </div>
     </el-col>
    </el-row>

    <el-row v-if="!readonly">
      <el-col :span="23" style="text-align: center">
        <el-button type="info" @click="$router.go(-1)">取消</el-button>
        <el-button :loading="addIng" type="primary" @click="update()">保存</el-button>
      </el-col>
    </el-row>

    <!-- 弹出层 -->
    <SelectTicket :select-show="selectShow" :value="addData.ticketBoxList" :excludeBoxIds="excludeBoxIds" @close="selectShow = false" @selectTicket="selectTicket"   v-if="selectShow"/>
    <!-- 弹出层 -->
    <ChannelTicket :channel-show="channelShow" :value="channelList" :excludeChannelIds="excludeChannelIds" @close="channelShow = false" @channelTicket="channelTicket"   v-if="channelShow"/>
  </div>
</template>
<script>
import Upload from '@/components/ImageUpload'
import SelectTicket from './components/selectTicket'
import ChannelTicket from './components/channelTicket'
import { publicFileGetUrl } from '@/api/common'
import { getCouponDetail, addCoupon } from '@/api/business/coupon'
import { accDiv, accMul } from '@/utils/util'
import {addData} from "../../../api/system/dict/data";
export default {
  name: 'CouponAdd',
  components: {
    Upload,
    SelectTicket,
    ChannelTicket
  },
  data() {
    return {
      IMG_URL: publicFileGetUrl,
      id: this.$route.query.id,
      readonly: this.$route.name === 'CouponQuery',
      channelList: [],
      addData: {
        ticketBoxList:[],
        useArea: 5,
        dueDays: 90,
        type: 2,
        channelSharedRate:0,
        minOrderAmt:0,
        status: '',
      },
      addIng: false,
      excludeBoxIds: [],
      excludeChannelIds: [],
      selectShow: false,
      channelShow: false,
      rules: {
        title: [{ required: true, message: '请输入券名称', trigger: 'blur' }],
        type: [{ required: true, message: '请输入券类型', trigger: 'blur' }],
        quantity: [
          { required: true, message: '请输入券发放数量', trigger: 'blur' },
          { pattern: /^([1-9]\d*)$/, message: "请输入正确的数量", trigger: ["blur", "change"] }
        ],
        discount: [
          { required: true, message: '请输入券面值', trigger: 'blur' },
          { pattern: /^([1-9]\d*(\.\d{1,2})?|([0](\.([0][1-9]|[1-9]\d{0,1}))))$/, message: "请输入正确的面值，最多两位小数", trigger: ["blur", "change"] }
        ],
        channelSharedRate: [
          { required: true, message: '请输入门店默认承担比例', trigger: 'blur' },
          { pattern: /^([0-9]\d*)$/, message: "请输入正确的百分比数字", trigger: ["blur", "change"] }
        ],
        minOrderAmt: [
          { required: true, message: '请输入最低消费金额', trigger: 'blur' },
          { pattern: /^(([1-9]\d*)|0)(\.\d{1,2})?$/, message: "请输入正确的金额，最多两位小数", trigger: ["blur", "change"] }
        ],
        dueDays: [
          { required: true, message: '请选择有效期', trigger: 'blur' },
          // { pattern: /^([1-9]\d*)$/, message: "请输入正确的数字", trigger: ["blur", "change"] }
        ],
        description: [{ required: false, message: '请输入使用说明', trigger: 'blur' }],
        useArea: [{ required: true, message: '请选择使用范围', trigger: 'blur' }]
      }
    }
  },
  created() {
    if (this.id) {
      getCouponDetail(this.id).then(res => {
        const { couponId, title, quantity, discount, channelSharedRate, minOrderAmt, dueDays, description, ticketBoxList, channelList, status } = res.data
        this.addData = {
          type: JSON.parse(res.data.type).value,
          useArea: JSON.parse(res.data.useArea).value,
          status: JSON.parse(res.data.status).value,
          discount: accDiv(discount, 100),
          minOrderAmt: accDiv(minOrderAmt, 100),
          couponId, title, quantity, channelSharedRate, dueDays, description, ticketBoxList
        }
        this.channelList = channelList
      })
    }
  },
  methods: {
    funSelectShow(){
      this.excludeBoxIds = this.addData.ticketBoxList.map(item => { return item.boxId })
      this.selectShow = true
    },
    funChannelShow(){
      this.excludeChannelIds = this.channelList.map(item => { return item.channelId })
      this.channelShow = true
    },
    selectTicket(select) {
      this.addData.ticketBoxList = this.addData.ticketBoxList.concat(select)
    },
    channelTicket(select) {
      this.channelList = this.channelList.concat(select)
    },
    update() {
      if (this.addData.type == 1) {
        if(this.addData.useArea !== 0 && this.addData.useArea !== 1 && this.addData.useArea !== 3 && this.addData.useArea !== 4) {
          this.$message({
            message: '请选择使用范围！',
            type: 'warning'
          })
          return
        }
      } else if (this.addData.type == 2) {
        if(this.addData.useArea !== 2 && this.addData.useArea !== 0 && this.addData.useArea !== 1 ) {
          this.$message({
            message: '请选择使用范围！',
            type: 'warning'
          })
          return
        }
      }
      this.$refs.addItem.validate((valid, items) => {
        if (valid) {
          this.addIng = true
          if(this.addData.useArea === 1 && this.addData.type === 1) {
            this.addData.boxIds = this.addData.ticketBoxList.map(item => { return item.boxId }).toString()
          }
          if(this.addData.useArea === 1 && this.addData.type === 2) {
            let arr = []
            for (let i = 0; i < this.channelList.length; i++) {
              arr.push(this.channelList[i].channelId)
            }
            this.addData.channelIdList = arr
          }
          const { discount, minOrderAmt, ...rest } = this.addData
          addCoupon({...rest, ...{ discount: accMul(discount, 100), minOrderAmt: accMul(minOrderAmt, 100),}}).then(res => {
            this.addIng = false
            if (res.code === 0) {
              this.$message({
                message: this.addData.couponId ? '修改成功!' : '添加成功!',
                type: 'success'
              })
              this.$store.dispatch('tagsView/delView', this.$route)
              this.$router.go(-1)
            }
          }).catch(() => {
            this.addIng = false
          })
        } else {
          if (items && Object.keys(items).length > 0) {
            this.$message({
              message: items[Object.keys(items)[0]][0].message,
              type: 'warning'
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.tip {
  font-size: 12px;
  color: #888;
}
</style>
