<template>
  <div class="setmeal">
    <div class="setmeal__h">
      <p class="setmeal__h--p"> {{ updateId ? $t('setmealadd_11') : $t('setmealadd_10') }} </p>
    </div>

    <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="100" class="setmeal__form">
      <FormItem class="formitem" :label="$t('design_28')+'：'" prop="product_type">
          <RadioGroup v-model="formValidate.product_type" @on-change="changeType">
              <Radio label="api_buy">{{ $t('setmealadd_6') }}</Radio>
              <Radio label="api_free">{{ $t('setmealadd_7') }}</Radio>
              <Radio label="product_more">{{ $t('product_more') }}</Radio>
          </RadioGroup>
      </FormItem>
      <FormItem class="formitem" :label="$t('setmealadd_1')+'：'" prop="product_name">
          <Input clearable v-model="formValidate.product_name"  style="width: 600px;" />
      </FormItem>

      <!-- 接口或套餐 -->
      <FormItem class="formitem" v-if="formValidate.product_type != 'product_more'" :label="$t('api_service')+'：'" prop="product_key">
        <Select clearable v-model="formValidate.product_key" style="width:600px">
            <Option v-for="(item, index) in allService" :value="item.service" :key="'service'+index+item.service">{{ item.service }}-{{ item.title}}</Option>
        </Select>
      </FormItem>
      <FormItem class="formitem" v-else :label="$t('service_product')+'：'" prop="product_key_more">
        <CheckboxGroup v-model="formValidate.product_key_more" >
        <Checkbox v-for="(pItem,index) in apiPayProductList" :key="'product' + index + pItem.id" :label="pItem.id + ''">
        {{pItem.id}}. {{pItem.product_name}} ({{pItem.amount}}{{$t('time')}}/{{pItem.price}}{{$t('setmeallist_3')}})
        </Checkbox>
        </CheckboxGroup>    
      </FormItem>

      <FormItem class="formitem" v-if="formValidate.product_type != 'product_more'" :label="$t('setmealadd_2')+'：'" prop="amount">
          <Input clearable v-model="formValidate.amount" style="width: 600px" />{{$t('time')}}
      </FormItem>

      <FormItem class="formitem" :label="$t('setmealadd_3')+'：'" prop="price">
          <Input clearable  :disabled="formValidate.product_type == 'api_free'" v-model="formValidate.price" style="width: 600px" />{{$t('setmeallist_3')}}
      </FormItem>
      <FormItem class="formitem" :label="$t('setmealadd_4')+'：'" prop="expire_time">
          <!-- <Input clearable v-model="formValidate.expire_time" style="width: 600px" /> -->
          <Select clearable v-model="formValidate.expire_time" style="width:600px" >
            <Option v-for="item in timeList" :value="item.key" :key="'time' + item.key">{{ item.name}}</Option>
        </Select>
      </FormItem>
      <FormItem class="formitem" :label="$t('setmealadd_5')+'：'" prop="product_desc">
         <!--  <Input clearable type="textarea" :autosize="{minRows: 3,maxRows: 8}" v-model="formValidate.product_desc" style="width: 600px" /> -->
         <quill-editor class="inputbox" v-model="formValidate.product_desc" :options="quillOption"  style="width: 600px"></quill-editor>
      </FormItem>
      <FormItem class="formitem" :label="$t('status')+'：'" prop="product_status">
        <RadioGroup v-model="formValidate.product_status" @on-change="changeStatus">
              <Radio label="1">{{$t('setmealadd_8')}}</Radio>
              <Radio label="0">{{$t('setmealadd_9')}}</Radio>
          </RadioGroup>
      </FormItem>
      <FormItem class="application__btn">
        <Button type="primary" v-if="!updateId" @click="addSetMeal">{{$t('save')}}</Button>
        <Button type="primary" v-else @click="updateSetMeal">{{$t('setmealadd_15')}}</Button>
      </FormItem>
    </Form>
  </div>
</template>

<script>
// ListAllRightsService
import { ListAllRightsService, GetExpireTimeList, GetProduct, CreateProduct, UpdateProduct, GetPayProductListForMore } from '@/api/setmeal'
import { getToken } from '@/libs/util'
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import Quill from 'quill'
import ImageResize from 'quill-image-resize-module'
import quillConfig from '../quillEditor.config'
Quill.register('modules/imageResize', ImageResize)
export default {
  components: {
    quillEditor
  },

  data () {
    return {
      quillOption: quillConfig,
      updateId: 0,
      setmealTitle: '',
      access_token: getToken(),
      allService: [], // 接口数组
      timeList: [], // 接口数组
      apiPayProductList: [], // 套餐
      formValidate: {
        product_name: '', // 套餐名
        product_key: '', // 接口名
        product_key_more: [], // 多套餐
        product_type: 'api_buy', // 套餐类型
        price: '0.00', // 价格
        amount: '100', // 数量
        expire_time: '', // 有效时间
        product_desc: ' ', // 说明
        product_status: '1', // 套餐状态
      },
      ruleValidate: {
        product_name: [
          { required: true, message: this.$t('setmealadd_12'), trigger: 'blur' }
        ],
        product_key: [
          // { required: true, message: this.$t(''), trigger: 'blur' }
        ],
        product_type: [
          { required: true, message: this.$t(''), trigger: 'blur' }
        ],
        price: [
          { required: true, message: this.$t('setmealadd_14'), trigger: 'blur' }
        ],
        amount: [
          // { required: true, message: this.$t('setmealadd_13'), trigger: 'blur' }
          { message: this.$t('input_integer_warning'), pattern: /^\+?[1-9][0-9]*$/ }
        ],
        expire_time: [
          { required: true, message: this.$t(''), trigger: 'blur', type:'number' }
        ],
        product_status: [
          { required: true, message: this.$t(''), trigger: 'blur' }
        ]
      }
    }
  },
  created(){
    this.isUpdate()
    if(this.updateId){
      this.getProduct(this.updateId)
    }
    this.getTimeList()
    this.getAllService()
    this.getPayProductListForMore()
  },
  methods: {
    // 修改还是新增
    isUpdate(){
      this.updateId = this.$route.query.id
    },
    // 获取套餐时间
    getTimeList(){
      let access_token = this.access_token
      GetExpireTimeList({access_token}).then(res=>{
        this.timeList = res.data
        this.formValidate.expire_time = this.timeList[0].key
      })
    },
    getPayProductListForMore() {
      let access_token = this.access_token
      GetPayProductListForMore({access_token}).then(res=>{
        this.apiPayProductList = res.data.items
      })
    },
    // 获取全部接口名
    getAllService(){
      let access_token = this.access_token
      ListAllRightsService({access_token}).then(res=>{
        this.allService = res.data.items
        //this.formValidate.product_key = this.allService[0].service
        if(!this.updateId) {
          this.formValidate.product_key = this.allService[0].service
        }
      })
    },
    // 获取指定套餐详情
    getProduct(id){
      // let access_token = this.access_token
      const formdata = new FormData()
      formdata.append('access_token', this.access_token)
      formdata.append('id', id)
      GetProduct(formdata).then(res=>{
        this.formValidate = res.data.product
        this.formValidate.product_status = this.formValidate.product_status + ''
        this.formValidate.amount = this.formValidate.amount + ''
      })
    },
    // 更新套餐
    updateSetMeal(){
      let _this = this
      _this.$refs['formValidate'].validate((val) => {
        if (!val) {
          _this.$Message.error(_this.$t('input_error_please_check_again'))
          return
        } else {
          _this.changeSetMeal(UpdateProduct,_this.updateId)
        }
      })
    },
    // 添加套餐
    addSetMeal(){
      this.$refs['formValidate'].validate((val) => {
        if (!val) {
          this.$Message.error(this.$t('input_error_please_check_again'))
          return
        } else {
          this.changeSetMeal(CreateProduct)
        }
      })
    },
    // 调用add、update接口
    changeSetMeal(api,id){
      let _this = this
      const setMealData = new FormData()
      setMealData.append('id',id) // 更新时
      setMealData.append('access_token',_this.access_token) //必须
      setMealData.append('product_name',_this.formValidate.product_name) //必须
      setMealData.append('product_key',_this.formValidate.product_key) //必须
      setMealData.append('product_type',_this.formValidate.product_type) //必须 免费去价格
      setMealData.append('price',_this.formValidate.price) //必须 免费为0
      setMealData.append('amount',_this.formValidate.amount + '') // >0
      setMealData.append('expire_time',_this.formValidate.expire_time)
      setMealData.append('product_key_more', _this.formValidate.product_key_more.join(',')) // 组合套餐

      if(_this.formValidate.product_desc) {
        setMealData.append('product_desc',_this.formValidate.product_desc)
      }
      setMealData.append('product_status',_this.formValidate.product_status)
      api(setMealData).then(res=>{
        if(res.ret == 200 && res.data.id){
          this.$Message.success(this.$t('add_successfully'))
          this.$router.push({name: 'setMealList'})
        }else if(res.ret == 200 && res.data.isUpdate){
          this.$Message.success(this.$t('update_successfully'))
          this.$router.push({name: 'setMealList'})
        } else {
          this.$Message.error(res.msg)
          // this.$Message.error(this.$t('update_successfully'))
        }
      })
    },
    // 改变类型
    changeType(value){
      this.formValidate.product_type = value
      if(value == 'api_free') {
        this.formValidate.price = '0.00'
      }
    },

    // 改变状态
    changeStatus(value){
      this.formValidate.product_status = value
    }
  }
}
</script>

<style  lang='scss'>
.setmeal {
  &__h{
    height:72px;
    background:rgba(255,255,255,1);
    box-shadow:0px 0px 30px 0px rgba(0,0,0,0.05);
    border-radius:10px;
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    justify-content: space-between;
    padding: 0 30px;
    &--p{
      font-size:16px;
      font-family:PingFangSC-Medium,PingFang SC;
      font-weight:500;
      color:rgba(35,35,42,1);
    }
  }
  &__form{
    display: flex;
    text-align: left;
    flex-direction: column;
    box-shadow:0px 0px 30px 0px rgba(0,0,0,0.05);
    border-radius:10px;
    background: #fff;
    padding-top: 20px;
    &--box{
      display: flex;
      margin-top: 30px;
    }
  }
}
.ql-toolbar.ql-snow + .ql-container.ql-snow {
  height: 250px;
}
</style>
