<template>

  <div>
    <div style=" position: relative;" class="">
      <el-tabs v-model="activeName2" type="card">
        <el-tab-pane label="未审核" name="ReviewManageAwaited">

        </el-tab-pane>
        <el-tab-pane label="已通过" name="ReviewManageAccepted">

        </el-tab-pane>
        <el-tab-pane label="已驳回" name="ReviewManageRejected">

        </el-tab-pane>
      </el-tabs>
    </div>

    <div style=" background-color: #fff; padding:15px;">




      <div style="margin-top:2px; margin-bottom:15px;" class="inline-block-btn-list">
        <el-select
          v-show="false"
          v-model="filter.point_type"
          @change="onFilterChanged"
          class="gap-right-8"
          style="width:90px;"
        >
          <el-option
            v-for="item in pointTypes"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-date-picker
          class="gap-right-8 first-element-btn"
          v-model="filter.time_range"
          type="daterange"
          value-format="timestamp"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="instantPickerOptions"
          @change="onFilterChanged"
        ></el-date-picker>
        <div class="gap-right-8" style="display:inline-block; width:280px;">
          <el-input
            placeholder="输入关键词查找（事件内容）"
            ref="search-bar"
            v-model="filter.keywords"
            class="input-with-select"
            @keyup.enter.native="onFilterChanged"
          >
            <el-button slot="append" icon="el-icon-search" @click="onFilterChanged"></el-button>
          </el-input>
        </div>

        <IntegralCreateApplicationBtn @sendsuccess="onFilterChanged" :btn_type="1"></IntegralCreateApplicationBtn>
      </div>
      <el-table
        v-loading="loading"
        ref="multipleTable"
        :data="tableData"
        :border="false"
        tooltip-effect="dark"
        style="width: 100%"
      >



        <el-table-column prop="target_name" label="姓名"></el-table-column>

        <el-table-column prop="category_path" label="积分分类"></el-table-column>
        <el-table-column label="积分规则">
          <template slot-scope="scope">
            <div v-if="scope.row.rule_name && scope.row.item_content">
              {{ scope.row.rule_name }}：<br/>
              {{ scope.row.item_content }}
            </div>
            <div v-else>未指定</div>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="多人审批">
          <template slot-scope="scope">
            <span v-for="review_item of scope.row.review_list" :key="review_item.reviewer_id" v-if="review_item.status === 0" style="color: #aaa">
              <el-tooltip :content="review_item.name+'待审核'" placement="top">
                <span>
                  {{review_item.name+' '}}
                </span>
              </el-tooltip>
            </span>
            <span v-for="review_item of scope.row.review_list" :key="review_item.reviewer_id" v-if="review_item.status === 1" style="color: green">
                  <el-tooltip :content="review_item.name+'审核通过，得分'+review_item.point+'分'" placement="top">
                   <span>
                    {{review_item.name+' '}}
                   </span>
                 </el-tooltip>
            </span>
            <span v-for="review_item of scope.row.review_list" :key="review_item.reviewer_id" v-if="review_item.status === -1" style="color: red">
                <el-tooltip :content="review_item.name+'驳回,原因:'+review_item.comment" placement="top">
                <span>
                  {{review_item.name+' '}}
                </span>
               </el-tooltip>
            </span>

            <!-- <span v-bind:class="scope.row.point < 0 ? 'point-negative' : 'point-positive'">{{ scope.row.point }}</span> -->
          </template>
        </el-table-column>
        <el-table-column prop="point_type" label="积分">

          <template slot-scope="scope">
            <div v-html="pointTypeFormatter(scope.row)"></div>
          </template>

        </el-table-column>
        <el-table-column label="事件日期">
          <template slot-scope="scope">
            <i v-if="scope.row.event_time" class="el-icon-time"></i>
            <span>{{dateFormatter('','',scope.row.event_time)}}</span>
          </template>
        </el-table-column>





        <el-table-column label="操作" width="165">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="openEditDialog(scope.row.event_id)"
              :disabled="scope.row.can_edit == false"
            >查看</el-button>
            <el-button
              type="text"
              @click="confirmDelete(scope.row.event_id)"
              :disabled="scope.row.can_edit == false"
            >撤消</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="prev, pager, next"
        :page-size="10"
        :page-sizes="[10, 20, 50, 100]"
        :total="totalCount"
        :current-page.sync="currentPage"
        @current-change="changePage"
      ></el-pagination>
      <!-- 新增积分弹窗 -->
      <el-dialog
        title="积分申请"
        :visible.sync="dialogCreateVisible"
        :close-on-click-modal="false"
        @open="initialCreateDialog"
        width="650px"
      >
        <el-form
          ref="newApplicationForm"
          :model="newApplicationForm"
          :rules="rules"
          @submit.native.prevent
          style="padding-right:15px;"
        >
          <el-form-item label="事件日期" prop="event_time" :label-width="formLabelWidth">
            <el-date-picker
              v-model="newApplicationForm.event_time"
              type="date"
              value-format="timestamp"
              placeholder="选择日期"
              :picker-options="assistantOptions"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="事件内容" prop="remark" :label-width="formLabelWidth">
            <el-input
              v-model="newApplicationForm.remark"
              auto-complete="off"
              placeholder="输入事件内容（最多100字）"
              type="textarea"
              :rows="3"
              resize="none"
              style="margin-top:5px;"
            ></el-input>
          </el-form-item>
          <el-form-item label="审核人" prop="reviewer_id" :label-width="formLabelWidth">
            <template>
              <el-select v-model="newApplicationForm.reviewer_id" placeholder="选择审核人">
                <el-option
                  v-for="item in reviewerOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                  <span>{{ item.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.dept_name }}</span>
                </el-option>
              </el-select>
            </template>
          </el-form-item>
          <el-form-item label="自主指定积分规则" prop="determine_rule" :label-width="formLabelWidth">
            <el-switch class="gap-right-15" v-model="newApplicationForm.determine_rule"></el-switch>
          </el-form-item>
          <el-form-item
            label="积分分类"
            prop="category_id"
            :label-width="formLabelWidth"
            v-show="newApplicationForm.determine_rule"
          >
            <el-cascader
              clearable
              :options="categoryTree"
              change-on-select
              v-model="newApplicationForm.category_id"
              @change="loadAvailableRuleItems(newApplicationForm)"
              placeholder="选择积分分类"
            ></el-cascader>
          </el-form-item>
          <el-form-item
            label="积分规则"
            prop="rule_item_id"
            :label-width="formLabelWidth"
            v-show="newApplicationForm.determine_rule"
          >
            <el-select
              v-model="newApplicationForm.rule_item_id"
              @change="updatePointIndicatorInCreateDialog"
              :disabled="!newApplicationForm.category_id || newApplicationForm.category_id.length == 0"
            >
              <el-option-group
                v-for="group in availableRuleItems"
                :key="group.id"
                :label="group.name"
              >
                <el-option
                  v-for="item in group.options"
                  :key="item.id"
                  :label="item.content"
                  :value="item.id"
                ></el-option>
              </el-option-group>
            </el-select>
            <br>
            <span
              v-show="newApplicationForm.rule_item_id"
            >标准： {{ newApplicationForm.pointIndicatorText }}</span>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogCreateVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitCreateForm('newApplicationForm')">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 编辑积分弹窗 -->
      <el-dialog
        title="积分申请"
        :visible.sync="dialogEditVisible"
        :close-on-click-modal="false"
        width="650px"
      >
        <el-form
          ref="applicationForm"
          :model="applicationForm"
          :rules="rulesEdit"
          @submit.native.prevent
          style="padding-right:15px;"
        >
          <el-form-item label="事件日期"   prop="event_time" :label-width="formLabelWidth">
            <el-date-picker
             disabled
              v-model="applicationForm.event_time"
              type="date"
              value-format="timestamp"
              placeholder="选择日期"
              :picker-options="assistantOptions"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="事件内容" prop="remark" :label-width="formLabelWidth">
            <el-input
              v-model="applicationForm.remark"
              auto-complete="off"
              placeholder="输入事件内容（最多100字）"
              type="textarea"
              :rows="3"
              resize="none"
              disabled
              style="margin-top:5px;"
            ></el-input>
          </el-form-item>
          <el-form-item label="审核人" prop="reviewer_id" :label-width="formLabelWidth">
            <template>
              <el-select v-model="applicationForm.reviewer_id" disabled placeholder="选择审核人">
                <el-option
                  v-for="item in reviewerOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                  <span>{{ item.name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{ item.dept_name }}</span>
                </el-option>
              </el-select>
            </template>
          </el-form-item>
          <el-form-item
            v-if="settings.review_set.indexOf('can_set_category') >= 0"
            label="自主指定积分规则"
            prop="determine_rule"
            :label-width="formLabelWidth"
          >
            <el-switch  :active-value="false" v-model="applicationForm.determine_rule"></el-switch>
          </el-form-item>
          <el-form-item
            label="积分分类"
            prop="category_id"
            :label-width="formLabelWidth"
            
          >
            <el-cascader
              clearable
              disabled
              :options="categoryTree"
              change-on-select
              v-model="applicationForm.category_id"
              @change="loadAvailableRuleItems(applicationForm)"
              placeholder="选择积分分类"
            ></el-cascader>
          </el-form-item>
          <el-form-item
            label="积分规则"
            prop="rule_item_id"
            :label-width="formLabelWidth"
           
          >
            <el-select
              v-model="applicationForm.rule_item_id"
              disabled
              @change="updatePointIndicatorInEditDialog"
              :disabled="!applicationForm.category_id || applicationForm.category_id.length == 0"
            >
              <el-option-group
                v-for="group in availableRuleItems"
                :key="group.id"
                :label="group.name"
              >
                <el-option
                  v-for="item in group.options"
                  :key="item.id"
                  :label="item.content"
                  :value="item.id"
                ></el-option>
              </el-option-group>
            </el-select>
            <br>
            <span v-show="applicationForm.rule_item_id">标准： {{ applicationForm.pointIndicatorText }}</span>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogEditVisible = false">取 消</el-button>
          <el-button style="display: none;" disabled type="primary" @click="submitEditForm('applicationForm')">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>


</template>
<script>
import IntegralCreateApplicationBtn from '@/views/dashboard/components/IntegralCreateApplicationBtn'
export default {
  components: {
    IntegralCreateApplicationBtn
  },
  data() {
    const validateRemark = (rule, value, callback) => {
      const validValue = value
        ? value.replace(/\s/g, '').replace(/&nbsp;/gi, '')
        : value
      if (!validValue) {
        return callback(new Error('请填写事件内容'))
      } else {
        callback()
      }
    }
    const validateReviewer = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请选择审核人'))
      } else {
        callback()
      }
    }
    const validateCategory = (rule, value, callback) => {
      if (
        this.newApplicationForm.determine_rule &&
        (!value || value.length == 0)
      ) {
        return callback(
          new Error('您已勾选自主指定积分规则，请选择积分分类后再提交')
        )
      } else {
        callback()
      }
    }
    const validateRuleItem = (rule, value, callback) => {
      if (this.newApplicationForm.determine_rule && !value) {
        return callback(
          new Error('您已勾选自主指定积分规则，请选择积分规则后再提交')
        )
      } else {
        callback()
      }
    }
    return {
      activeName2: 'ReviewManageAwaited',
      pageLimit: 10,
      profile: this.$store.getters.user_info,
      settings: this.$store.getters.system_setting,
      totalCount: 0,
      tableData: null,
      currentPage: 1,
      dialogCreateVisible: false,
      dialogEditVisible: false,
      pointTypes: [],
      filter: {
        keywords: '',
        point_type: 0,
        time_range: ''
      },
      newApplicationForm: {
        event_time: '',
        remark: '',
        determine_rule: false,
        category_id: [],
        rule_item_id: '',
        reviewer_id: '',
        pointIndicatorText: ''
      },
      application_status: 0,
      loading: false,
      applicationForm: {
        id: '',
        event_time: '',
        remark: '',
        determine_rule: false,
        category_id: [],
        rule_item_id: '',
        reviewer_id: '',
        pointIndicatorText: ''
      },
      categoryTree: [],
      rules: {
        remark: [{ validator: validateRemark, trigger: 'change' }],
        reviewer_id: [{ validator: validateReviewer, trigger: 'change' }],
        category_id: [{ validator: validateCategory, trigger: 'change' }],
        rule_item_id: [{ validator: validateRuleItem, trigger: 'change' }]
      },
      rulesEdit: {
        remark: [{ validator: validateRemark, trigger: 'change' }]
      },
      formLabelWidth: '140px',
      assistantOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
        shortcuts: [
          {
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          }
        ]
      },
      instantPickerOptions: {
        shortcuts: [
          {
            text: '本周',
            onClick(picker) {
              const now = new Date(new Date().toLocaleDateString())
              const start =
                now.getTime() - (now.getDay() - 1) * 24 * 60 * 60 * 1000
              const end = start + 7 * 24 * 60 * 60 * 1000 - 1000
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '上周',
            onClick(picker) {
              const now = new Date(new Date().toLocaleDateString())
              const start =
                now.getTime() - (now.getDay() + 6) * 24 * 60 * 60 * 1000
              const end = start + 7 * 24 * 60 * 60 * 1000 - 1000
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '本月',
            onClick(picker) {
              const now = new Date()
              const startDate = new Date(now.getFullYear(), now.getMonth(), 1)
              const endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0)
              picker.$emit('pick', [startDate.getTime(), endDate.getTime()])
            }
          },
          {
            text: '上月',
            onClick(picker) {
              const now = new Date()
              const startDate = new Date(
                now.getFullYear() - (now.getMonth() > 0 ? 0 : 1),
                (now.getMonth() + 11) % 12,
                1
              )
              const endDate = new Date(now.getFullYear(), now.getMonth(), 0)
              picker.$emit('pick', [startDate.getTime(), endDate.getTime()])
            }
          }
        ]
      },
      reviewerOptions: [],
      availableRuleItems: []
    }
  },
  watch:{
    'activeName2': function (val, old) {
      if(val == 'ReviewManageAwaited'){
        this.application_status = 0;
      }

      if(val == 'ReviewManageAccepted'){
        this.application_status = 1;
      }

      if(val == 'ReviewManageRejected'){
        this.application_status = -1;
      }

      this.onFilterChanged()
    }
  },
  methods: {
    pointTypeFormatter: function(row) {
      for (let index = 0; index < this.pointTypes.length; index++) {
        const pointType = this.pointTypes[index]

        // console.log(row, pointType.value)

        if (row.point_type == pointType.value) {
          if(row.point > 0){
            return '<span style="color:#f00;">+' +row.point +pointType.label+ '</span>'
          }else if(row.point < 0){
            return '<span style="color:#1a8dff;">' +row.point +pointType.label+ '</span>'
          }else{
            return row.point +pointType.label
          }
        }
      }
      return ''
    },
    onFilterChanged: function() {
      this.currentPage = 1
      this.loadApplicationList()
    },
    changePage: function(current) {
      if (isNaN(current) || current < 1) {
        return false
      }
      this.loadApplicationList()
    },
    dateFormatter: function(row, column, cellValue) {
      return this.$moment(cellValue * 1000).format('YYYY年MM月DD日')
    },
    dateTimeFormatter: function(row, column, cellValue) {
      return cellValue
        ? this.$moment(cellValue * 1000).format('YYYY-MM-DD HH:mm')
        : ''
    },
    reviewStatusFormatter: function(row, column, cellValue) {
      if (cellValue == 0) {
        return '待审核'
      } else if (cellValue == 1) {
        return '已通过'
      } else {
        return '被驳回'
      }
    },
    initialCreateDialog: function() {
      if (!this.newApplicationForm.event_time) {
        this.newApplicationForm.event_time = new Date().getTime()
      }
      if (this.reviewerOptions.length > 0) {
        this.newApplicationForm.reviewer_id = this.reviewerOptions[0].id
      }
    },
    showCreateDialog: function() {
      this.dialogCreateVisible = true
    },
    updatePointIndicatorInCreateDialog: function(currentVal) {
      this.newApplicationForm.pointIndicatorText = this.generatePointIndicator(
        currentVal
      )
    },
    updatePointIndicatorInEditDialog: function(currentVal) {
      this.applicationForm.pointIndicatorText = this.generatePointIndicator(
        currentVal
      )
    },
    generatePointIndicator: function(val) {
      for (let i = 0; i < this.availableRuleItems.length; i++) {
        for (let j = 0; j < this.availableRuleItems[i].options.length; j++) {
          const item = this.availableRuleItems[i].options[j]
          if (val == item.id) {
            const propertyText = item.is_negative == 1 ? '扣除' : '奖励'
            const valueText =
              item.is_range == 1
                ? item.value_1 + '～' + item.value_2
                : item.value_1
            let typeText = ''
            for (let index = 0; index < this.pointTypes.length; index++) {
              const pointType = this.pointTypes[index]
              if (item.point_type == pointType.value) {
                typeText = pointType.label
                break
              }
            }
            const indicatorText =
              propertyText + '  ' + valueText + '  ' + typeText
            return indicatorText
          }
        }
      }
    },
    loadPointType: function() {
      var self = this
      this.$http('get','/integral.php/ajax_request_common/get_point_types')
        .then(function(response) {
          if (response.status == 200) {
            const jsonData = response.data
            try {
              self.pointTypes = jsonData
            } catch (err) {
              console.log(err)
            }
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    // 选择积分分类时更新积分规则
    loadAvailableRuleItems: function(form) {
      const categoryPath = form.category_id
      if (!categoryPath || categoryPath.length == 0) {
        return
      }
      var self = this
      this.$http('get','/integral.php/ajax_request_common/get_grouped_rule_items',{category_id: categoryPath[categoryPath.length - 1]})
        .then(function(response) {
          if (response.status == 200) {
            const jsonData = response.data
            try {
              self.availableRuleItems = jsonData
              form.rule_item_id = ''
              form.pointIndicatorText = ''
            } catch (err) {
              console.log(err)
            }
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    loadApplicationList: function() {
      const params = {
        // applicant_id: this.profile.id,
        // page: this.currentPage

        reviewer_id: 0,
        status: this.application_status,
        page: this.currentPage,
        interval: this.pageLimit,
        target_id: this.profile.id
      }
      for (const item in this.filter) {
        const value = this.filter[item]
        if (item == 'time_range') {
          if (!value || value.length < 2) {
            continue
          }
          const timeRangeArr = value.map(x => parseInt(x / 1000))
          timeRangeArr[1] += 60 * 60 * 24 - 1
          params[item] = timeRangeArr.join(',')
        } else {
          params[item] = value
        }
      }
      var self = this
      self.loading = true
      // this.$http.get('/integral.php/ajax_request_common/get_integral_applications', {//get_application_list
      this.$http('get','/integral.php/ajax_request_common/get_application_list',params)
        .then(function(response) {
          if (response.status == 200) {
            self.loading = false
            var jsonData = response.data
            try {
              self.totalCount = jsonData.total_count
              self.tableData = jsonData.list_data
            } catch (err) {
              console.log(err)
            }
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    openEditDialog: function(eventId) {
      this.loadWidgetData()
      this.loadApplicationDetail(eventId)
      // var self = this;
      // this.loadWidgetData(() => {
      //     self.loadApplicationDetail(eventId);
      // });
    },
      // 获取控件所需数据
    loadWidgetData: function(callback) {
      var self = this
      this.$http('get','/integral.php/ajax_request_common/prepare_integral_options',{
            id: this.profile.id,
            category_tree: 1,
            superior_list: 1
          })
        .then(function(response) {
          if (response.status == 200) {
            var jsonData = response.data
            console.log("程度上")
            console.log(jsonData);
            try {
              self.categoryTree = jsonData.category_tree
              self.reviewerOptions = jsonData.reviewer_list
              if (callback) {
                callback.call()
              }
            } catch (err) {
              console.log(err)
            }
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    loadApplicationDetail: function(eventId) {
      var self = this
      this.$http('get','/integral.php/ajax_request_common/get_application_info',{id: eventId})
        .then(function(response) {
          if (response.status == 200) {
            const jsonData = response.data
            console.log("详情")
             console.log(jsonData);
            try {
              console.log('jsonData-----------?//1221')
              console.log(jsonData)
              self.availableRuleItems = jsonData.available_rule_items
              const applicationInfo = self.processDetailData(
                jsonData.application_info
              )
              for (const key in applicationInfo) {
                self.applicationForm[key] = applicationInfo[key]
              }
              self.dialogEditVisible = true
            } catch (err) {
              console.log(err)
            }
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    processDetailData: function(object) {
      // 时间戳转换
      object.event_time *= 1000
      object.reviewer_id =
        !isNaN(object.reviewer_id) && object.reviewer_id > 0
          ? parseInt(object.reviewer_id)
          : ''
      if (
        !isNaN(object.rule_item_id) &&
        object.rule_item_id > 0 &&
        object.category_id
      ) {
        object.determine_rule = true
        object.category_id = object.category_id
          .toString()
          .split(',')
          .map(Number)
        object.rule_item_id = object.rule_item_id
        this.updatePointIndicatorInEditDialog(object.rule_item_id)
      } else {
        object.determine_rule = false
        object.category_id = []
        object.rule_item_id = ''
      }
      return object
    },
    // 积分新增
    submitCreateForm: function(formName) {
      var form = this.$refs[formName]
      var self = this
      form.validate(valid => {
        if (valid) {
          if (form) {
            self.sendCreateRequest()
          }
        } else {
          // console.log('验证未通过');
          return false
        }
      })
    },
    // 积分新增
    sendCreateRequest: function() {
      const dataObj = this.newApplicationForm
      const formData = {}
      for (const item in dataObj) {
        if (item == 'category_id') {
          continue
        }
        if (item == 'event_time') {
          formData[item] = parseInt(dataObj[item] / 1000)
        } else if (item == 'determine_rule') {
          formData[item] = dataObj[item] ? 1 : 0
        } else {
          formData[item] = dataObj[item]
        }
      }
      formData['applicant_id'] = this.profile.id
      var self = this
      this.$http('post','/integral.php/ajax_request_common/add_integral_application',formData,'','',
        {transformRequest: [
          data => {
            const paramArray = new Array()
            for (const it in data) {
              paramArray.push(
                encodeURIComponent(it) + '=' + encodeURIComponent(data[it])
              )
            }
            return paramArray.join('&')
          }
        ]},
        // headers: {
        //   'Content-Type': 'application/x-www-form-urlencoded'
        // }
      )
        .then(function(response) {
          let message = ''
          let status = 0
          if (response.status == 200) {
            const data = response.data
            status = isNaN(data.status) ? 0 : parseInt(data.status)
            switch (status) {
              case 1:
                message = '积分申请提交成功'
                break
              case -1:
                message = '表单参数错误'
                break
              default:
                message = data.info ? data.info : '积分申请提交失败'
            }
          } else {
            message = '服务器出现问题'
          }
          self.$message({
            message: message,
            type: status == 1 ? 'success' : 'error'
          })
          if (status == 1) {
            self.currentPage = 1
            self.dialogCreateVisible = false
            self.loadApplicationList()
            self.resetCreateDialog()
          }else {

          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
     // 编辑积分申请
    submitEditForm: function(formName) {
      console.log(this.applicationForm.reviewer_id);
      var form = this.$refs[formName]
      var self = this
      form.validate(valid => {
        if (valid) {
          if (form) {
            self.sendEditRequest()
          }
        } else {
          // console.log('验证未通过');
          return false
        }
      })
    },
    // 积分申请修改
    sendEditRequest: function() {
      const dataObj = this.applicationForm
      const formData = {
        id: dataObj.id,
        event_time: parseInt(dataObj.event_time / 1000),
        remark: dataObj.remark,
        determine_rule: dataObj.determine_rule ? 1 : 0,
        reviewer_id: dataObj.reviewer_id,
        rule_item_id: dataObj.rule_item_id
      }
      var self = this
      this.$http('post','integral.php/ajax_request_common/update_integral_application',formData,'','',
        {transformRequest: [
          data => {
            const paramArray = new Array()
            for (const it in data) {
              paramArray.push(
                encodeURIComponent(it) + '=' + encodeURIComponent(data[it])
              )
            }
            return paramArray.join('&')
          }
        ]},
        // headers: {
        //   'Content-Type': 'application/x-www-form-urlencoded'
        // }
      )
        .then(function(response) {
          let message = ''
          let status = 0
          if (response.status == 200) {
            const data = response.data
            status = isNaN(data.status) ? 0 : parseInt(data.status)
            switch (status) {
              case 1:
                message = '积分申请修改成功'
                break
              case -1:
                message = '表单参数错误'
                break
              default:
                message = data.info ? data.info : '积分申请修改失败'
            }
          } else {
            message = '服务器出现问题'
          }
          self.$message({
            message: message,
            type: status == 1 ? 'success' : 'error'
          })
          if (status == 1) {
            self.loadApplicationList()
            self.dialogEditVisible = false
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    resetCreateDialog: function() {
      const form = this.$refs['newApplicationForm']
      form.clearValidate()
      form.resetFields()
    },
    confirmDelete(eventId) {
      this.$confirm('确定要撤消此积分申请吗?', '撤消积分申请', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.deleteItem(eventId)
        })
        .catch(() => {
          // console.log('已取消删除');
        })
    },
    deleteItem(eventId) {
      if (!eventId) {
        return false
      }
      var self = this
      this.$http('get','/integral.php/ajax_request_common/delete_integral_application',{id: eventId})
        .then(function(response) {
          let message = ''
          let status = 0
          if (response.status == 200) {
            var data = response.data
            status = isNaN(data.status) ? 0 : parseInt(data.status)
            switch (status) {
              case 1:
                message = '撤消积分申请成功'
                break
              case -1:
                message = '表单参数错误'
                break
              default:
                message = data.info ? data.info : '撤消积分申请失败'
            }
          } else {
            message = '服务器出现问题'
          }
          self.$message({
            message: message,
            type: status == 1 ? 'success' : 'error'
          })
          if (status == 1) {
            self.loadApplicationList()
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    }
  },
  created() {
    this.loadPointType()
    this.loadApplicationList()
  }
}
</script>
<style>
.el-pagination {
  text-align: center;
  margin-top: 15px;
}
</style>
