<template>
  <div>
    <el-tabs v-model="activeName2" type="card">
      <el-tab-pane label="工龄分" name="type_1">

      </el-tab-pane>
      <el-tab-pane label="初始分" name="type_2">

      </el-tab-pane>


      <el-tab-pane label="考勤分" name="type_3" v-if="false">

      </el-tab-pane>
      <el-tab-pane v-if="settings.point_set.indexOf('a') >= 0" label="A分" name="type_0">

      </el-tab-pane>


    </el-tabs>


<EmployeeAPoint v-if="activeName2 == 'type_0'"></EmployeeAPoint>

    <div class="jfsj" style="background-color: #fff; padding:15px;" v-if="activeName2 != 'type_0'">
      <div style="margin-top:2px; margin-bottom:15px;" class="inline-block-btn-list">
        <el-button class="first-element-btn" :disabled="multipleSelection.length < 1" @click="confirmMultipleDelete" type="primary" plain>批量删除
        </el-button>
        <el-select
          v-show="false"
          v-model="filter.target_id_set"
          filterable
          multiple
          :multiple-limit="3"
          placeholder="选择员工进行筛选（最多3个）"
          @change="onFilterChanged"
          class="gap-right-8"
          style="width:290px;">
          <el-option
            v-for="item in employeeOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
        <el-cascader v-if="false"
          clearable
          :options="categoryTree"
          change-on-select
          v-model="filter.category_id"
          @change="onFilterChanged"
          placeholder="分类筛选"
          style="width:120px"
          class="gap-right-8">
        </el-cascader>
        <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
          v-show="false"
          class="gap-right-8"
          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:250px;">
          <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>
        <el-button v-if="false" @click="dialogExcelVisible = true" type="primary" plain>Excel管理
        </el-button>
        <el-button v-if="false" @click="dialogCreateVisible = true" type="primary" plain>录入事件</el-button>
        <el-button v-if="activeName2 == 'type_0'" @click="" type="primary" plain>A分清零</el-button>



      </div>
      <el-table
        v-loading="loading"
        ref="multipleTable"
        :data="tableData"
        :border="false"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="42"></el-table-column>
        <el-table-column prop="target_name" label="姓名"></el-table-column>
        <el-table-column prop="dept_name" label="部门"></el-table-column>
        <el-table-column  v-if="activeName2 != 'type_1' && activeName2 != 'type_2'" prop="category_path" :show-overflow-tooltip="true" label="积分分类"></el-table-column>
        <el-table-column v-if="activeName2 != 'type_1' && activeName2 != 'type_2'" label="积分规则" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <div>{{ scope.row.rule_name }}：</div>
            <div>{{ scope.row.item_content }}</div>
          </template>
        </el-table-column>
        <el-table-column  v-if="activeName2 != 'type_1' && activeName2 != 'type_2'" prop="remark" label="备注" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="分值">
          <template slot-scope="scope">
            <span v-bind:class="scope.row.point < 0 ? 'point-negative' : 'point-positive'">{{ scope.row.point }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="unactivated" label="状态" :formatter="reviewStatusFormatter"></el-table-column>
        <el-table-column prop="event_time" label="事件日期" :formatter="dateFormatter"
                         min-width="130"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="text" @click="openEditDialog(scope.row.id)">编辑</el-button>
            <el-button type="text" @click="confirmDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="total,sizes, prev, pager, next"
        :page-size="pageLimit"
        :page-sizes="[10, 20, 50, 100]"
        :total="totalCount"
        @size-change="handleSizeChange"
        :current-page.sync="currentPage"
        @current-change="changePage">
      </el-pagination>
      <el-dialog
        title="积分事件录入"
        width="600px"
        :visible.sync="dialogCreateVisible"
        :close-on-click-modal="false"
        @open="setDefaultValueForDialog">
        <el-form ref="newEventForm" :model="newEventForm" :rules="rules" @submit.native.prevent>
          <el-form-item label="奖扣对象" prop="target_id_set" :label-width="formLabelWidth">
            <el-select
              v-model="newEventForm.target_id_set"
              filterable
              multiple
              :multiple-limit="10"
              placeholder="选择员工（最多10个）" style="width:300px;">
              <el-option
                v-for="item in employeeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="事件日期" prop="event_time" :label-width="formLabelWidth">
            <el-date-picker
              v-model="newEventForm.event_time"
              type="date"
              value-format="timestamp"
              placeholder="选择日期"
              :picker-options="assistantOptions" style="width:300px;">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="积分分类" prop="category_id" :label-width="formLabelWidth">
            <el-cascader
              :options="categoryTree"
              change-on-select
              v-model="newEventForm.category_id"
              @change="loadAvailableRules(newEventForm)"
              placeholder="选择分类进行筛选" style="width:300px;">
            </el-cascader>
          </el-form-item>
          <el-form-item label="积分规则" prop="rule_id" :label-width="formLabelWidth">
            <el-select
              v-model="newEventForm.rule_id"
              :disabled="!newEventForm.category_id || newEventForm.category_id.length == 0"
              @change="loadAvailableItems(newEventForm, initializeItemData)" style="width:300px;">
              <el-option
                v-for="item in availableRuleOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id" style="width:300px;">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            v-for="(item, key) in newEventForm.items"
            label="加分选项"
            :key="item.id"
            :prop="'items.' + key"
            :rules="itemRules"
            style="padding-left:10px; padding-right:10px;">
            <el-checkbox
              v-model="item.checked"
              :label="item.content"
              border>
            </el-checkbox>


            <el-input-number
              label="加分分数"
              class="gap-left-8"
              v-model="item.point"
              :min="item.value_1"
              :max="item.is_range ? item.value_2 : item.value_1"
              v-show="item.checked" style="margin-top:20px; width:300px;">
            </el-input-number>


            <span class="gap-left-8" v-show="item.checked">
                        {{ generatePointIndication(item) }}
                    </span>

            <el-form-item
              class="gap-top-8"
              v-model="item.remark"
              v-show="item.checked"
              auto-complete="off" style="margin-top:20px; width:380px;">
              <el-input placeholder="备注" type="textarea"></el-input>
            </el-form-item>


          </el-form-item>

        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogCreateVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitCreateForm('newEventForm')">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog title="事件编辑" width="650px" :visible.sync="dialogEditVisible" :close-on-click-modal="false"
                 @close="onDismissEditDialog">
        <el-form ref="eventForm" :model="eventForm" @submit.native.prevent>
          <el-form-item label="奖扣对象" :label-width="formLabelWidth">
            <span>{{ eventForm.target_name }}</span>
          </el-form-item>
          <el-form-item label="事件日期" prop="event_time" :label-width="formLabelWidth">
            <el-date-picker
              v-model="eventForm.event_time"
              type="date"
              value-format="timestamp"
              placeholder="选择日期"
              :picker-options="assistantOptions">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="积分分类" v-if="activeName2 != 'type_1' && activeName2 != 'type_2'" :label-width="formLabelWidth">
            <span>{{ eventForm.category_path }}</span>
          </el-form-item>
          <el-form-item v-if="activeName2 != 'type_1' && activeName2 != 'type_2'" label="积分规则" :label-width="formLabelWidth">
            <span>{{ eventForm.rule_name }}</span>
          </el-form-item>
          <el-form-item v-if="activeName2 != 'type_1' && activeName2 != 'type_2'" prop="item" style="padding-left:10px; padding-right:10px;">
                    <span class="gap-left-8">
                        {{ eventForm.item.content + ' ' + generatePointIndication(eventForm.item) }}
                    </span>
            <el-input-number
              class="gap-left-8"
              ref="pointEditor"
              v-model="eventForm.point"
              :min="eventForm.item.value_1"
              :max="eventForm.item.is_range ? eventForm.item.value_2 : eventForm.item.value_1">
            </el-input-number>
            <br/>

            <el-input style="margin-top:15px;" type="textarea" v-model="eventForm.remark"></el-input>
          </el-form-item>


          <el-form-item label="积分" v-if="activeName2 == 'type_1' || activeName2 == 'type_2'" prop="item"　:label-width="formLabelWidth">

            <el-input-number
              class="gap-left-8"
              ref="pointEditor"
              v-model="eventForm.point">
            </el-input-number>
            <br/>
          </el-form-item>


        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogEditVisible = false">取 消</el-button>
          <el-button type="primary" @click="sendEditRequest">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog
        title="积分事件Excel导入"
        :visible.sync="dialogExcelVisible"
        :close-on-click-modal="false"
        class="dialog-type-section">
        <el-row :gutter="15">
          <el-col :span="10">
            <div class="align-center gap-bottom-15">
              <el-upload
                action="/integral.php/excel_util/test_link"
                :show-file-list="false"
                :http-request="uploadFile">
                <el-button type="primary">Excel导入</el-button>
                <div slot="tip" class="el-upload__tip">支持上传大小500KB以内的Excel文件</div>
              </el-upload>
            </div>
            <div class="align-center">
              <el-button
                type="primary"
                :disabled="!selectedItems || selectedItems.length == 0"
                @click="downloadTemplate">下载模板
              </el-button>
              <div class="tooltip">请选择积分规则后下载生成的Excel模板文件</div>
            </div>
            <el-form :model="itemSelectForm" style="margin-top:30px;" @submit.native.prevent>
              <el-form-item label="积分分类" prop="category_id" :label-width="formLabelWidth">
                <el-cascader
                  :options="categoryTree"
                  change-on-select
                  v-model="itemSelectForm.category_id"
                  @change="loadAvailableRules(itemSelectForm)"
                  placeholder="选择分类进行筛选">
                </el-cascader>
              </el-form-item>
              <el-form-item label="积分规则" prop="rule_id" :label-width="formLabelWidth">
                <el-select
                  v-model="itemSelectForm.rule_id"
                  :disabled="!itemSelectForm.category_id || itemSelectForm.category_id.length == 0"
                  @change="loadAvailableItems(itemSelectForm, applyItemSelection)">
                  <el-option
                    v-for="item in availableRuleOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item
                v-for="(item, key) in itemSelectForm.items"
                :key="item.id"
                :prop="'items.' + key"
                style="padding-left:10px; padding-right:10px;">
                <el-checkbox
                  v-model="item.checked"
                  :label="item.content + '（' + generatePointIndication(item) + '）'"
                  border
                  @change="updateItemSelection(item, $event)">
                </el-checkbox>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="14">
            <div style="font-size:15px; padding: 12px;">已选择积分规则</div>
            <div style="padding:5px; max-height: 100%; overflow-y: auto;">
              <el-table
                :show-header="false"
                :data="selectedItems"
                empty-text="未选中任何积分规则"
                style="width: 100%">
                <el-table-column>
                  <template slot-scope="scope">
                    <div>{{ scope.row.category_path + ' - ' + scope.row.rule_name }}</div>
                    <div>{{ scope.row.content + '（' + generatePointIndication(scope.row) + '）' }}</div>
                  </template>
                </el-table-column>
                <el-table-column width="80">
                  <template slot-scope="scope">
                    <el-button type="danger" icon="el-icon-delete"
                               @click="removeItemSelection(scope.row.id)"></el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-col>
        </el-row>
      </el-dialog>
    </div>

  </div>

</template>
<script>
  import EmployeeAPoint from '@/views/integral/EmployeeAPoint'
export default {
    components: {
      EmployeeAPoint
    },
    data() {
      const validateTarget = (rule, value, callback) => {
        if (!value || value.length == 0) {
          return callback(new Error('请选择奖扣积分对象'))
        } else {
          callback()
        }
      }
      const validateCategory = (rule, value, callback) => {
        if (!value || value.length == 0) {
          return callback(new Error('请选择积分分类'))
        } else {
          callback()
        }
      }
      const validateRule = (rule, value, callback) => {
        if (!value || isNaN(value)) {
          return callback(new Error('请选择积分规则'))
        } else {
          callback()
        }
      }
      const validateItem = (rule, value, callback) => {
        if (isNaN(value.point) || parseInt(value.point) == 0) {
          return callback(new Error('请填写有效的积分数值'))
        }
        callback()
      }
      return {
        settings: this.$store.getters.system_setting,
        activeName2: 'type_1',
        profile: this.$store.getters.user_info,
        totalCount: 0,
        tableData: null,
        currentPage: 1,
        pageLimit: 20,
        multipleSelection: [],
        loading: false,
        dialogCreateVisible: false,
        dialogEditVisible: false,
        dialogExcelVisible: false,
        formLabelWidth: '90px',
        newEventForm: {
          target_id_set: [],
          category_id: [],
          rule_id: '',
          event_time: '',
          items: []
        },
        eventForm: {
          id: '',
          target_name: '',
          event_time: '',
          category_path: '',
          rule_name: '',
          point: '',
          remark: '',
          item: {
            content: '',
            is_range: false,
            is_negative: false,
            point_type: '',
            value_1: 0,
            value_2: 0
          }
        },
        itemSelectForm: {
          target_id_set: [],
          category_id: [],
          rule_id: '',
          event_time: '',
          items: [],
          get_category: 1
        },
        selectedItems: [],
        rules: {
          target_id_set: [
            { validator: validateTarget, trigger: 'change' }
          ],
          category_id: [
            { validator: validateCategory, trigger: 'change' }
          ],
          rule_id: [
            { validator: validateRule, trigger: 'change' }
          ]
        },
        itemRules: {
          validator: validateItem, trigger: 'change'
        },
        deptTree: [],
        filter: {
          keywords: '',
          target_id_set: [],
          category_id: [],
          point_type: 0,
          time_range: ''
        },
        categoryTree: [],
        employeeOptions: [],
        pointTypes: [],
        availableRuleOptions: [],
        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()])
            }
          }]
        }
      }
    },
    watch: {
      activeName2(val, old) {
        this.onFilterChanged()
      }
    },
    methods: {
      onFilterChanged: function() {
        this.currentPage = 1
        this.loadEventList()
      },
      reviewStatusFormatter: function(row, column, cellValue) {
        return cellValue == 1 ? '待审核' : '已生效'
      },
      dateFormatter: function(row, column, cellValue) {
        return this.$moment(cellValue * 1000).format('YYYY年MM月DD日')
      },
      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)
        })
      },
      toggleSelection: function(rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row)
          })
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      },
      // 选择积分分类时更新积分规则
      loadAvailableRules: function(formObj) {
        if (!formObj) {
          return
        }
        const categoryPath = formObj.category_id
        if (!categoryPath || categoryPath.length == 0) {
          return
        }
        var self = this
        this.$http('get','/integral.php/ajax_request_common/get_integral_rules_by_category',{
            category_id: categoryPath[categoryPath.length - 1]}).then(function(response) {
          if (response.status == 200) {
            const jsonData = response.data
            try {
              self.availableRuleOptions = jsonData
              formObj.rule_id = ''
              formObj.items = []
            } catch (err) {
              console.log(err)
            }
          }
        }).catch(function(error) {
          console.log(error)
        })
      },
      // 选择积分规则时更新细则列表
      loadAvailableItems: function(formObj, callback) {
        if (!formObj) {
          return
        }
        const ruleId = formObj.rule_id
        if (isNaN(ruleId) || ruleId < 0) {
          return
        }
        const params = {
          rule_id: ruleId
        }
        if (formObj.get_category) {
          params.get_category = formObj.get_category
        }
        this.$http('get','/integral.php/ajax_request_common/get_integral_items_by_rule',params).then(function(response) {
          if (response.status == 200) {
            let jsonData = response.data
            try {
              if (callback) {
                jsonData = callback.call(null, jsonData)
              }
              formObj.items = jsonData
            } catch (err) {
              console.log(err)
            }
          }
        }).catch(function(error) {
          console.log(error)
        })
      },
      initializeItemData: function(jsonData) {
        for (let index = 0; index < jsonData.length; index++) {
          const item = jsonData[index]
          item.checked = false
          item.point = item.value_1
          item.remark = ''
        }
        return jsonData
      },
      applyItemSelection: function(jsonData) {
        const selectedItemIds = this.selectedItems.map(x => x.id)
        for (let index = 0; index < jsonData.length; index++) {
          const item = jsonData[index]
          item.checked = selectedItemIds.indexOf(item.id) > -1
        }
        return jsonData
      },
      generatePointIndication: function(item) {
        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
          }
        }
        return '标准： ' + propertyText + '  ' + valueText + '  ' + typeText
      },
      handleSelectionChange: function(val) {
        this.multipleSelection = val
      },
      // 获取积分事件列表
      loadEventList: function() {
        const params = {
          // recorder_id: this.profile.id,
          page: this.currentPage,
          interval: this.pageLimit
        }
        for (const item in this.filter) {
          const value = this.filter[item]
          if (item == 'target_id_set') {
            if (!value || value.length == 0) {
              continue
            }
            params[item] = value.join(',')
          } else if (item == 'category_id') {
            if (!value || value.length == 0) {
              continue
            }
            params[item] = value[value.length - 1]
          } else 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
        if (self.activeName2 == 'type_1') {
          params['remark'] = '工龄分'
          delete params['time_range']
        }
        if (self.activeName2 == 'type_2') {
          params['remark'] = '初始积分'
          delete params['time_range']
        }
        this.$http('get','/integral.php/ajax_request_common/get_integral_records',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)
        })
      },
      handleSizeChange(val) {
        this.pageLimit = val
        this.onFilterChanged()
      },
      changePage: function(current) {
        if (isNaN(current) || current < 1) {
          return false
        }
        this.loadEventList()
      },
      resetCreateDialog: function() {
        const form = this.$refs['newEventForm']
        form.clearValidate()
        this.newEventForm.rule_id = ''
        this.newEventForm.items = []
      },
      openEditDialog: function(eventId) {
        var self = this
        this.$http('get','/integral.php/ajax_request_common/get_event_detail',{id: eventId}).then(function(response) {
          if (response.status == 200) {
            const jsonData = response.data
            try {
              self.eventForm = self.processDetailData(jsonData)
              self.dialogEditVisible = true
            } catch (err) {
              console.log(err)
            }
          }
        }).catch(function(error) {
          console.log(error)
        })
      },
      onDismissEditDialog: function() {
        const form = this.$refs['eventForm']
        form.clearValidate()
        this.eventForm = {
          id: '',
          target_name: '',
          event_time: '',
          category_path: '',
          rule_name: '',
          point: '',
          remark: '',
          item: {
            content: '',
            is_range: false,
            is_negative: false,
            point_type: '',
            value_1: 0,
            value_2: 0
          }
        }
      },
      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.newEventForm
        const formData = {}
        let emptyItems = false
        for (const item in dataObj) {
          if (item == 'category_id') {
            continue
          }
          if (item == 'items') {
            const checkedRuleItems = dataObj[item].filter(x => x.checked)
            if (!checkedRuleItems || checkedRuleItems.length == 0) {
              emptyItems = true
              break
            }
            formData[item] = JSON.stringify(checkedRuleItems)
          } else if (item == 'target_id_set') {
            formData[item] = dataObj[item].join(',')
          } else if (item == 'event_time') {
            formData[item] = parseInt(dataObj[item] / 1000)
          } else {
            formData[item] = dataObj[item]
          }
        }
        if (emptyItems) {
          this.$message({
            message: '没有选中积分细则',
            type: 'error'
          })
          return
        }
        formData['recorder_id'] = this.profile.id
        var self = this
        this.$http('post','/integral.php/ajax_request_common/record_integral_event',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.loadEventList()
            self.resetCreateDialog()
          }
        }).catch(function(error) {
          console.log(error)
        })
      },
      sendEditRequest: function() {
        const dataObj = this.eventForm
        if (isNaN(dataObj.point) || !dataObj.point) {
          this.$message({
            message: '请填写积分数值',
            type: 'error'
          })
          this.$refs['pointEditor'].focus()
          return
        }
        let formData = {}
        if (this.activeName2 == 'type_1' || this.activeName2 == 'type_2') {
          formData = {
            id: dataObj.id,
            event_time: parseInt(dataObj.event_time / 1000),
            point: dataObj.point,
            remark: dataObj.remark,
            is_negative: 0
          }
        } else {
          formData = {
            id: dataObj.id,
            event_time: parseInt(dataObj.event_time / 1000),
            point: dataObj.point,
            remark: dataObj.remark,
            is_negative: dataObj.item.is_negative
          }
        }
        var self = this
        this.$http('post','/integral.php/ajax_request_common/update_event',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 = '修改积分事件失败'
            }
          } else {
            message = '服务器出现问题'
          }
          self.$message({
            message: message,
            type: status == 1 ? 'success' : 'error'
          })
          if (status == 1) {
            self.loadEventList()
            self.dialogEditVisible = false
          }
        }).catch(function(error) {
          console.log(error)
        })
      },
      confirmDelete(eventId) {
        this.$confirm('确定要删除此积分事件吗?', '删除积分事件', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.deleteItem(eventId)
        }).catch(() => {
          // console.log('已取消删除');
        })
      },
      confirmMultipleDelete() {
        if (this.multipleSelection.length < 1) {
          return false
        }
        this.$confirm('确定要删除选中的积分事件吗?', '批量删除积分事件', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const targetArr = []
          for (const index in this.multipleSelection) {
            targetArr.push(this.multipleSelection[index].id)
          }
          const targetIds = targetArr.join(',')
          this.deleteItem(targetIds, true)
        }).catch(() => {
          // console.log('已取消删除');
        })
      },
      deleteItem(eventId, isMultiple) {
        if (!eventId) {
          return false
        }
        isMultiple = isMultiple || false
        let url = ''
        let params = null
        if (isMultiple) {
          url = '/integral.php/ajax_request_common/delete_event_multiple'
          params = {
            ids: eventId
          }
        } else {
          url = '/integral.php/ajax_request_common/delete_event'
          params = {
            id: eventId
          }
        }
        var self = this
        this.$http('get',url,params).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.loadEventList()
          }
        }).catch(function(error) {
          console.log(error)
        })
      },
      // 获取控件所需数据
      loadWidgetData: function() {
        var self = this
        this.$http('get','/integral.php/ajax_request_common/prepare_integral_options',{
            id: this.profile.id,
            category_tree: 1,
            employee_list: 1
          }).then(function(response) {
          if (response.status == 200) {
            var jsonData = response.data
            try {
              self.categoryTree = jsonData.category_tree
            } catch (err) {
              console.log(err)
            }
          }
        }).catch(function(error) {
          console.log(error)
        })
      },
      // 获取可录入积分对象的列表
      loadTargetRange: function() {
        var self = this
        this.$http('get','/integral.php/ajax_request_common/load_target_range',{
            recorder_id: this.profile.id
          }).then(function(response) {
          if (response.status == 200) {
            var jsonData = response.data
            try {
              self.employeeOptions = jsonData
            } catch (err) {
              console.log(err)
            }
          }
        }).catch(function(error) {
          console.log(error)
        })
      },
      setDefaultValueForDialog: function() {
        if (!this.newEventForm.event_time) {
          this.newEventForm.event_time = new Date().getTime()
        }
      },
      processDetailData: function(object) {
        // 时间戳转换
        object.event_time *= 1000
        return object
      },
      updateItemSelection: function(item, checked) {
        if (checked) {
          const itemIds = this.selectedItems.map(x => x.id)
          if (itemIds && (itemIds.length == 0 || itemIds.indexOf(item.id) < 0)) {
            this.selectedItems.push(item)
          }
        } else {
          this.selectedItems = this.selectedItems.filter(x => {
            if (x.id != item.id) {
              return x
            }
          })
        }
      },
      removeItemSelection: function(itemId) {
        const index = this.selectedItems.map(x => x.id).indexOf(itemId)
        if (!isNaN(index) && index > -1) {
          this.selectedItems.splice(index, 1)
          const itemArray = this.itemSelectForm.items
          for (let i = 0; i < itemArray.length; i++) {
            if (itemArray[i].id == itemId) {
              itemArray[i].checked = false
            }
          }
        }
      },
      // 上传文件
      uploadFile: function(params) {
        if (!params || !params.file) {
          return false
        }
        const formData = new FormData()
        formData.append('uploader_id', this.profile.id)
        formData.append('file', params.file)
        this.$http('post','/integral.php/excel_util/import_event_sheet', formData,'','multipart/form-data',
          // headers: {
          //   'Content-Type': 'multipart/form-data'
          // },
          {transformRequest: [function(data) {
            return data
          }]}
        ).then((response) => {
          const responseData = response.data
          if (responseData.errors && responseData.errors.length > 0) {
            const messageHead = responseData.info ? responseData.info : '导入完成'
            const h = this.$createElement
            const errorGroup = [h('p', null, messageHead + '。但文件中存在如下问题数据：')]
            for (let i = 0; i < responseData.errors.length; i++) {
              errorGroup.push(h('div', null, responseData.errors[i]))
            }
            const message = h('div', null, errorGroup)
            this.$alert(message, '导入结果', {
              confirmButtonText: '确定'
            })
          } else {
            this.$message({
              message: responseData.info ? responseData.info : '导入完成',
              type: responseData.status == 1 ? 'success' : 'error'
            })
          }
          if (responseData.status == 1) {
            this.loadRuleList()
          }
        }).catch(function(error) {
          console.log(error)
          return false
        })
      },
      // 下载模板
      downloadTemplate: function() {
        if (!this.selectedItems || this.selectedItems.length == 0) {
          return
        }
        const selectedItemIds = this.selectedItems.map(x => x.id).join(',')
        const url = '/integral.php/excel_util/download_event_template?site_id=' +
        this.profile.site_id + '&item_id_set=' + selectedItemIds
        window.open(url)
        // window.location.href = url;
      }
    },
    created() {
      this.loadWidgetData()
      this.loadPointType()
      this.loadTargetRange()
      this.loadEventList()
    }
  }
</script>

<style>
  .el-pagination {
    text-align: center;
    margin-top: 15px;
  }

  .jfsj .el-dialog__footer {
    text-align: center;
  }

  .jfsj .el-dialog__body {
    padding: 30px 70px 0 50px;
  }
</style>
