<template>
  <div class="setmeal">
    <div class="setmeal__h">
      <p class="setmeal__h--p"> {{$t('setmealmanage_1')}} </p>
      <Button type="primary" @click="openMealModalGrant()">{{$t('setmealmanage_2')}}</Button>
    </div>

    <Table border :loading="disabledTab" :columns="columnsList" :data="dataList" class="ListTab">
        <template slot-scope="{ row }" slot="used_amount" class="operation">
          <p style="color: red;">{{ row.used_amount }}</p>
        </template>
        <template slot-scope="{ row }" slot="used_percent" class="operation">
          <p>{{ row.used_percent + '%' }}</p>
        </template>
        <template slot-scope="{ row,index }" slot="operation" class="operation">
            <Button type="primary" size="small" class="operation__btn" @click="openMealModalDjust(row.id)">{{$t('setmealmanage_8')}}</Button>
            <Button class="ivu-btn ivu-btn-error ivu-btn-small operation__btn" type="text" size="small" @click="remove(row.id)">{{$t('delete')}}</Button>
        </template>
    </Table>
    <div class="pagination">
      <Page :total="total" show-elevator show-sizer @on-page-size-change='changeSize' @on-change='changePage'/>
    </div>

    <!-- 套餐发放 -->
    <Modal
        v-model="mealgrantmodal"
        :title="$t('setmealmanage_2')">
        <Form :model="mealData_grant" ref="mealData_grant" :rules="ruleValidate_grant" label-position="left" :label-width="100">
          <FormItem :label="$t('setmealadd_1')" prop="product_name">
              <Input v-model="mealData_grant.product_name"></Input>
          </FormItem>
          <FormItem :label="$t('api_service')" prop="product_key">
            <Select v-model="mealData_grant.product_key">
              <Option v-for="item in allService" :value="item.service" :key="item.service">{{item.service}}-{{ item.title }}</Option>
            </Select>
          </FormItem>
          <FormItem :label="$t('account')" prop="username">
              <Input v-model="mealData_grant.username"></Input>
          </FormItem>
          <FormItem :label="$t('setmealmanage_4')" prop="total_amount">
              <Input v-model="mealData_grant.total_amount"></Input>
          </FormItem>
          <FormItem :label="$t('setmealmanage_7')" prop="expire_time">
              <DatePicker v-model="mealData_grant.expire_time" type="datetime" @on-change="grantTime" style="width: 100%"></DatePicker>
        </Col>
          </FormItem>
        </Form>
        <div slot="footer">
          <Button @click="cancelGrant()">{{$t('cancel')}}</Button>
          <Button type="primary" @click="createMeal()">{{$t('save')}}</Button>
        </div>
    </Modal>

    <!-- 套餐调整 -->
    <Modal
        v-model="mealadjustmodal"
        :title="$t('setmealmanage_8')">
        <Form :model="mealData_djust" ref="mealData_djust" :rules="ruleValidate_djust" label-position="left" :label-width="100">
          <FormItem :label="$t('setmealmanage_4')" prop="total_amount">
              <Input v-model="mealData_djust.total_amount"></Input>
          </FormItem>
          <FormItem :label="$t('setmealmanage_7')" prop="expire_time">
              <DatePicker :value="mealData_djust.expire_time" type="datetime" @on-change="djustTime" style="width: 100%" format="yyyy-MM-dd HH:mm:ss"></DatePicker>
        </Col>
          </FormItem>
        </Form>
        <div slot="footer">
          <Button @click="cancelDjust()">{{$t('cancel')}}</Button>
          <Button type="primary" @click="changeMeal()">{{$t('save')}}</Button>
        </div>
    </Modal>
  </div>
</template>

<script>
import { ListAllRightsService, AddNewFlow, DeleteFlow, GetFlow, GetFlowList, UpdateFlow } from '@/api/setmeal'
import { getToken } from '@/libs/util'
import { getRelativeTime, getDateTime, getHandledValue } from '@/libs/tools'
export default {

  data () {
    return {
      disabledTab: false,
      mealgrantmodal: false,
      mealadjustmodal: false,
      setmealmanageId: 0,
      access_token: getToken(),
      allService: [],
      mealData_grant: {
        product_name: '',
        product_key: '',
        username: '',
        total_amount: '0',
        expire_time: ''
      },
      ruleValidate_grant: {
        product_name: [
          { required: true, message: this.$t('setmealadd_12'), trigger: 'blur' }
        ],
        product_key: [
          { required: true, message: this.$t(''), trigger: 'blur' }
        ],
        username: [
          { required: true, message: this.$t('setmealmanage_10'), trigger: 'blur' }
        ],
        total_amount: [
          { required: true, message: this.$t('setmealmanage_11'), trigger: 'blur' }
        ],
        expire_time: [
          // { required: true, message: this.$t('setmealadd_13'), trigger: 'blur' }
          // { message: this.$t('input_integer_warning'), pattern: /^\+?[1-9][0-9]*$/ }
        ]
      },
      mealData_djust: {
        total_amount: '0',
        expire_time: ''
      },
      ruleValidate_djust: {
        total_amount: [
          { required: true, message: this.$t('setmealmanage_11'), trigger: 'blur' }
        ],
        expire_time: [
          // { required: true, message: this.$t('setmealadd_13'), trigger: 'blur', type:'number' }
          // { message: this.$t('input_integer_warning'), pattern: /^\+?[1-9][0-9]*$/ }
        ]
      },
      columnsList: [
        {
          title: this.$t('account'),
          key: 'username',
          // slot: 'product_name',
          align: 'center'
        },
        {
          title: this.$t('setmealadd_1'),
          key: 'product_name',
          align: 'center',
          // slot: 'product_key',
          width: '120'
        },
        {
          title: this.$t('api_name'),
          key: 'product_key',
          // slot: 'product_type',
          align: 'center'
        },
        {
          title: this.$t('setmealmanage_4'),
          key: 'total_amount',
          align: 'center'
        },
        {
          title: this.$t('setmealmanage_5'),
          key: 'used_amount',
          slot: 'used_amount',
          align: 'center'
        },
        {
          title: this.$t('setmealmanage_6'),
          key: 'used_percent',
          align: 'center',
          slot: 'used_percent'
        },
        {
          title: this.$t('setmealmanage_7'),
          key: 'expire_time_str',
          // slot: 'product_status',
          align: 'center'
        },
        {
          title: this.$t('status'),
          key: 'flow_status_name',
          // slot: 'flow_status_name',
          align: 'center'
        },
        {
          title: this.$t('operation'),
          slot: 'operation',
          width: 200,
          align: 'center'
        }
      ],
      dataList: [],
      total: 0,
      page: 1, // 分页
      perpage: 10
    }
  },
  created () {
    this.queryList()
    this.getAllService()
  },
  methods: {
    // 赋值时间
    djustTime (val) {
      this.mealData_djust.expire_time = val
    },
    grantTime (val) {
      this.mealData_grant.expire_time = val
    },
    // 查询套餐
    queryList () {
      this.disabledTab = true
      const formdata = new FormData()
      formdata.append('access_token', this.access_token)
      formdata.append('page', this.page)
      formdata.append('perpage', this.perpage)
      GetFlowList(formdata).then(res => {
        this.disabledTab = false
        this.total = res.data.total
        this.dataList = res.data.items
      })
    },
    // 删除接口调用
    removeApi (id) {
      const access_token = this.access_token
      DeleteFlow({ access_token, id }).then(res => {
        this.$Message.success(this.$t('successfully_delete'))
        this.queryList()
      })
    },
    // 删除套餐
    remove (id) {
      this.$Modal.confirm({
        title: this.$t('operation_confirm'),
        content: `<p>${this.$t('setmealmanage_9')}</p>`,
        onOk: () => {
          this.removeApi(id)
        },
        onCancel: () => {
          this.$Message.info(this.$t('cancel'))
        }
      })
    },
    // 获取全部接口名
    getAllService () {
      let access_token = this.access_token
      ListAllRightsService({ access_token }).then(res => {
        this.allService = res.data.items
        this.mealData_grant.product_key = this.allService[0].service
      })
    },
    changeSize (size) {
      this.perpage = size
      this.queryList()
    },
    changePage (page) {
      this.page = page
      this.queryList()
    },
    // 发放套餐modal
    openMealModalGrant () {
      this.mealgrantmodal = true
    },
    cancelGrant () {
      this.mealgrantmodal = false
    },
    // 调整套餐modal
    openMealModalDjust (index) {
      this.mealadjustmodal = true
      this.setmealmanageId = index
      this.getMealInfo(index)
    },
    cancelDjust () {
      this.mealadjustmodal = false
    },
    // 获取套餐详情
    getMealInfo (index) {
      let _this = this
      let id = index
      let access_token = _this.access_token
      GetFlow({ id, access_token }).then(res => {
        _this.mealData_djust.total_amount = res.data.flow.total_amount + ''
        _this.mealData_djust.expire_time = getDateTime(res.data.flow.expire_time, 'year')
      })
    },
    // 调整套餐
    changeMeal () {
      this.$refs['mealData_djust'].validate((val) => {
        if (!val) {
          this.$Message.error(this.$t('input_error_please_check_again'))
        } else {
          let _this = this
          const formdata = new FormData()
          formdata.append('id', _this.setmealmanageId)
          formdata.append('access_token', _this.access_token)
          formdata.append('total_amount', _this.mealData_djust.total_amount)
          if (_this.mealData_djust.expire_time) {
            formdata.append('expire_time', _this.mealData_djust.expire_time)
          }
          UpdateFlow(formdata).then(res => {
            if (res.data.isUpdate) {
              _this.queryList()
              _this.$Message.success(_this.$t('update_successfully'))
              _this.mealadjustmodal = false
            } else {
              _this.$Message.error(res.msg || _this.$t('nothing_changed'))
            }
          })
        }
      })
    },
    // 发放套餐
    createMeal () {
      this.$refs['mealData_grant'].validate((val) => {
        if (!val) {
          this.$Message.error(this.$t('input_error_please_check_again'))
        } else {
          let _this = this
          const formdata = new FormData()
          formdata.append('access_token', _this.access_token)
          formdata.append('product_name', _this.mealData_grant.product_name)
          formdata.append('product_key', _this.mealData_grant.product_key)
          formdata.append('username', _this.mealData_grant.username)
          formdata.append('total_amount', _this.mealData_grant.total_amount)
          if (_this.mealData_grant.expire_time) {
            formdata.append('expire_time', _this.mealData_grant.expire_time)
          }
          AddNewFlow(formdata).then(res => {
            if (res.data.id) {
              _this.queryList()
              _this.$Message.success(_this.$t('add_successfully'))
              _this.mealgrantmodal = false
            } else {
              _this.$Message.error(res.msg)
            }
          })
        }
      })
    }
  }
}
</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;
      // margin-left: 30px;
      color:rgba(35,35,42,1);
    }
  }
}
.ListTab{
  background: #fff;
  border-radius: 10px;
}
.pagination {
  margin-top: 30px;
  display: flex;
  justify-content: flex-end;
}
.operation{
  &__btn{
    margin: 0 5px;
  }
}
</style>
