<template>
  <div class="sjp-freelist">
      <div>
        <Form ref="formInline"  :model="formInline" inline :label-width="80">
          <FormItem class="sjp-inlineblock"  label="奖品名称">
            <Input v-model="formInline.prizeName" placeholder="请输入奖品名称" style="width: 300px"/>
          </FormItem>
          <FormItem class="sjp-inlineblock"  label="时间筛选">
            <DatePicker type="datetimerange" v-model="timeArr" placeholder="选择开始时间和结束时间" style="width: 300px"></DatePicker>
          </FormItem>
          <FormItem class="sjp-inlineblock"  label="上架状态">
             <Select v-model="formInline.prizeStatus" style="width:200px">
                <Option v-for="item in statusList" :value="item.code" :key="item.code">{{ item.message }}</Option>
            </Select>
          </FormItem>
          <br>
           <position :positionObj="formInline" label="所在地" width="200"></position>
          <br>
          <FormItem :label-width="20">
            <div class="sjp-buttons">
              <Button type="primary" class="sjp-search sjp-button" @click="getData">搜索</Button>
              <Button type="default" class="sjp-button" @click="resetData">重置</Button>
              <Button type="primary" class="sjp-button sjp-add" @click="addPrize">新建</Button>
            </div>
          </FormItem>
      </Form>
      </div>
      <div class="order-table">
         <Table stripe :columns="columns" border :data="list"></Table>
      </div>
      <div class="sjp-page">
          <Page :total="total" :current.sync="formInline.pageCount" :page-size.sync="formInline.pageSize" @on-change="pageChange" @on-page-size-change="pageSizeChange" show-total show-sizer></Page>
      </div>

      <!-- 新建，编辑奖品 -->
       <Modal
        v-model="visibleModal"
        width="80%"
        class-name="free-dialog"
        :title="titleObj[titleStatus]"
        :mask-closable="false"
        @on-ok="saveHandle"
        @on-cancel="cancel">
          <div class="sjp-freedetail">
            <addOrEditPrize @initForm="initForm" :prizeId="prizeId" v-if="visibleModal && titleStatus !== 'look'"></addOrEditPrize>
            <lookPrize :prizeId="prizeId" v-if="visibleModal && titleStatus === 'look'"></lookPrize>
          </div>
          <div slot="footer"  style="text-align: center;">
            <div v-if="titleStatus === 'look'" >
              <Button type="default" size="large"  @click="close">关闭</Button>
            </div>
            <div v-else>
              <Button type="default" size="large"  @click="cancel">取消</Button>
              <Button type="primary" size="large"  :loading="loading"  @click="saveHandle">确定</Button>
            </div>
          </div>
      </Modal>
  </div>
</template>

<script>
import addOrEditPrize from './addOrEditPrize'
import position from './../../../components/position'
import lookPrize from './lookPrize'
import http from './../../service/statics'
import shopInfo from './../../service/shopinfo.js'
import Utils from './../../utils/utils'
export default {
  name: 'freelist',
  components: {  addOrEditPrize,lookPrize,position },
  props:[],
  data() {
    return {
      titleStatus:'add',
      titleObj:{
        add: '新建奖品',
        edit: '编辑奖品',
        similar: '相似新增',
        look: '详情'
      },
      visibleModal: false,
      loading: false,
      total: 0,
      border: true,
      prizeForm:null,
      columns: [
              {
                  title: '所属商圈',
                  key: 'belongRegion',
                  align: 'center',
                  width: '200',
                  render: (h, params) => {
                    return h('div', this.businessAreaObj[params.row.belongRegion]);
                  }
              },
              {
                  title: '报名时间',
                  key: 'joinStartTime',
                  align: 'center',
                  width: '200',
                  render: (h, params) => {
                          return h('div', params.row.joinStartTime  + ' - ' + params.row.joinEndTime);
                      }
              },
              {
                  title: '奖品名称',
                  key: 'prizeName',
                  align: 'center',
                  width: '200',
              },
               {
                  title: '中奖名额',
                  key: 'prizeWinQuantity',
                  align: 'center',
                  width: '100',
              },
               {
                  title: '上架状态',
                  key: 'prizeStatus',
                  align: 'center',
                  render: (h, params) => {
                          return h('div', this.statusObj[params.row.prizeStatus]);
                      }
              },
              {
                title: '操作',
                key: 'action',
                align: 'center',
                // fixed: 'right',
                width: 200,
                render: (h, params) => {
                  let status = params.row.prizeStatus; //1:待上架  2:上架  3:下架
                  const generateButton = (status)=>{
                    let arr = [h('Button', {
                            props: {
                                type: 'primary',
                                size: 'small'
                            },
                            style: {
                                      marginRight: '5px'
                                  },
                            on: {
                                click: () => {
                                  this.titleStatus = 'look'
                                  this.visibleModal = true
                                  this.prizeId = params.row.prizeId
                                }
                            }
                        }, '详情')]
                        if(status === 1){
                            arr.push(h('Button', {
                              props: {
                                  type: 'primary',
                                  size: 'small'
                              },
                              style: {
                                      marginRight: '5px'
                                  },
                              on: {
                                click: () => {
                                  this.titleStatus = 'edit'
                                  this.visibleModal = true
                                  this.prizeId = params.row.prizeId
                                }
                              }
                          }, '编辑'),
                          h('Button', {
                              props: {
                                  type: 'primary',
                                  size: 'small'
                              },
                              style: {
                                      marginRight: '5px'
                                  },
                              on: {
                                click: () => {
                                  http.manageOff({id: params.row.prizeId}).then(()=>{
                                    this.getData()
                                  })
                                }
                              }
                          }, '下架'))
                        } else if(status === 3) {
                          arr.push(h('Button', {
                            props: {
                                type: 'primary',
                                size: 'small'
                            },
                            style: {
                                    marginRight: '5px'
                                },
                            on: {
                                click: () => {
                                  this.titleStatus = 'similar'
                                  this.visibleModal = true
                                  this.prizeId = params.row.prizeId
                                }
                              }
                          }, '相似新建'))
                        }
                    return arr
                  }
                  return h('div', generateButton(status));
                }
            }
          ],
        list: [],
      timeArr:[], // 时间筛选数组
      formInline:{
        prizeName:'', // 奖品名称
        belongProvince:'', // 省
        belongCity:'',//市
        belongRegion:'',// 商圈
        joinEndTime:'', // 结束时间
        joinStartTime:'', //开始时间
        prizeStatus: '',// 状态
        pageCount:1,
        pageSize:10,
      },
      prizeId:'',
      statusList: [{
        code: '1',
        message:'待上架'
      },{
        code: '2',
        message:'已上架'
      },{
        code: '3',
        message:'已下架'
      }],
      statusObj: {}, // 根据key值寻找value
      formName:'',
      businessAreaObj:{},
    }
  },
  created() {
    this.statusList.forEach((item)=>{
      this.statusObj[item.code] = item.message
    })
    // 获取商圈信息列表
    shopInfo.getAllData({})
    .then((res) => {
      this.getData()
      let result = res.data || []
      result.forEach((item)=>{
        this.businessAreaObj[item.id] = item.name
      })
    })
  },
  methods:{
    // 初始化form
    initForm(formName, prizeForm){
      this.formName = formName
      this.prizeForm = prizeForm
    },
    // 重置
    resetData(){
     this.timeArr = [], // 时间筛选数组
      this.formInline = {
        prizeName:'', // 奖品名称
        belongProvince:'', // 省
        belongCity:'',//市
        belongRegion:'',// 商圈
        joinEndTime:'', // 结束时间
        joinStartTime:'', //开始时间
        prizeStatus:'',// 状态
        pageCount:1,
        pageSize:10,
      }
      this.getData()
    },
    // 获取数据
    getData(){
      // 更新时间
      this.formInline.joinStartTime = this.timeArr[0] && Utils.dealTime(this.timeArr[0]) || ''
      this.formInline.joinEndTime = this.timeArr[1] && Utils.dealTime(this.timeArr[1])|| ''
      http.manageList(this.formInline)
      .then((res)=>{
        this.list = res.data || []
        this.total = res.totalCount
      })
    },
    close(){
      this.visibleModal = false
    },
    saveHandle(){
      
     this.formName.validate((valid) => {
          if (valid) {
            if(this.loading){
              return
            }
            this.loading = true;
            let params = JSON.parse(JSON.stringify(this.prizeForm))
            this.changeFormat(params)
            params.prizePics = params.prizePics.join(',')
            if(!params.prizeId || this.titleStatus === 'similar'){
              params.prizeId = ''
              
              // 写死的userID
              params.prizeCreateUserId =  379913
              http.manageCreate(params)
              .then(() => {
                this.visibleModal = false
                this.getData()
                this.$Message.success('新建成功');
              }).finally(()=>{
                this.loading = false;
              })
            }else{
              http.manageModify(params)
               .then(() => {
                this.visibleModal = false
                this.getData()
                this.$Message.success('编辑成功');
              })
              .finally(()=>{
                this.loading = false;
              })

            }
          }
      })
    },
    cancel(){
      this.visibleModal = false
    },
    changeFormat(obj){
      let timeField = ['warmUpTime','joinEndTime','joinStartTime','prizeUseStartTime','prizeUseEndTime','prizeTime']
        timeField.forEach(item => {
          obj[item] = obj[item] && Utils.dealTime(obj[item]) || ''
        })
    },
     prefixZero(num) {
        return (Array(2).join(0) + num).slice(-2);
    },
    addPrize(){
      this.visibleModal = true
      this.titleStatus = 'add'
      this.prizeId = ''
    },
    pageSizeChange(val){
      this.formInline.pageSize = val
      // 如果当前也不是第一页会默认会更改为第一页，然后触发第一页的回调
      // 如果当前为第一页， 进行请求数据
      if(this.formInline.pageCount === 1){
        this.getData()
      }

    },
    pageChange(){
      this.getData()
    }
  },
  mounted(){
   
  }
}
</script>

<style lang="less" scoped>

  .sjp-freelist{
    .sjp-search{
      margin-right: 20px;
    }
    .sjp-buttons{
      width: calc(100vw - 400px);
    }
    .sjp-button{
      padding-left: 40px;
      padding-right: 40px;
    }
    .sjp-page{
      margin-top: 20px;
    }
    .sjp-add{
      float: right;
    }
  }
 
</style>
<style >

  .sjp-freedetail{
    height: calc(97vh - 200px);
    overflow-y: auto;
  }
  .free-dialog .ivu-modal{
    top: 5%;
  }
  .sjp-inlineblock .ivu-form-item-content{
    display: inline-block;
  }
</style>
