<template>
  <div style="display: inline;">
    <el-button @click="openCreateDialog" type="primary" plain style="margin-left:5px;">录入个人积分</el-button>
    <el-dialog
      top="50px"
      append-to-body
      title="PK积分事件录入"
      width="600px"
      height="300px"
      :visible.sync="dialogCreateVisible"
      :close-on-click-modal="false"
      @open="setDefaultValueForDialog">

      <el-form ref="newEventForm" :model="newEventForm" :rules="rules" @submit.native.prevent style="padding:0 30px;">
        <el-row :gutter="10">

          <el-col :span="6">
            <el-form-item prop="team_id_set">

              <el-select
                @change="setTeamId"
                v-model="newEventForm.team_id_set"
                filterable
                placeholder="选择团队">
                <el-option
                  v-for="item in teamOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>

            </el-form-item>
          </el-col>
          <el-col :span="18">
            <el-form-item prop="target_id_set">
              <el-select
                style="width:100%;"
                v-model="newEventForm.target_id_set"
                :disabled="newEventForm.team_id_set == 0"
                filterable
                multiple
                :multiple-limit="5"
                placeholder="选择员工（最多5个）">
                <el-option
                  v-for="item in memberList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>


        <el-form-item label="事件日期" prop="event_time" :label-width="formLabelWidth">
          <el-date-picker
            style="width:290px;"
            v-model="newEventForm.event_time"
            type="date"
            value-format="timestamp"
            placeholder="选择日期"
            :picker-options="assistantOptions">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="积分规则" prop="rule_id" :label-width="formLabelWidth">
          <el-select
            style="width:290px;"
            v-model="newEventForm.rule_id"
           >
           <!--  @change="loadAvailableItems(newEventForm, initializeItemData)" -->
            <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 label="备注内容" :label-width="formLabelWidth"
                      class="gap-top-8"
                      auto-complete="off" style="margin-top:20px;" prop="remark">
          <el-input placeholder="备注" v-model="newEventForm.remark" type="textarea" style="width:290px;"
                    :disabled="newEventForm.rule_id==0"></el-input>
        </el-form-item>
        <el-form-item label="积分数量" :label-width="formLabelWidth" prop="point">
          <el-input-number
            class="gap-left-8"
            v-model="newEventForm.point"
            :disabled="newEventForm.rule_id==0">
          </el-input-number>

        </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>
  </div>
</template>
<script>
  import qs from 'qs'

  export default {
    props: {
      pk_id: {
        type: String,
        default: ''
      }
    },
    data() {
      let validateTarget = (rule, value, callback) => {
        if (!value || value.length == 0) {
          return callback(new Error('请选择奖扣积分对象'))
        } else {
          callback()
        }
        callback()
        return true
      }

      let validateTeam = (rule, value, callback) => {
        if (!value || value == 0) {
          return callback(new Error('请选择一个团队'))
        } else {
          callback()
        }
      }


      let validateCategory = (rule, value, callback) => {
        if (!value || value.length == 0) {
          return callback(new Error('请选择积分分类'))
        } else {
          callback()
        }
      }
      let validateRule = (rule, value, callback) => {
        if (!value || isNaN(value)) {
          return callback(new Error('请选择积分规则'))
        } else {
          callback()
        }
      }
      let validateItem = (rule, value, callback) => {
        if (isNaN(value) || parseInt(value) == 0) {
          return callback(new Error('请填写有效的积分数值'))
        }
        callback()
      }
      let validateRemark = (rule, value, callback) => {
        if (value.length < 3) {
          return callback(new Error('至少填写3个字符'))
        }
        callback()
      }
      return {
        memberList: [],
        teamOptions: [],
        profile: this.$store.getters.user_info,
        totalCount: 0,
        tableData: null,
        currentPage: 1,
        multipleSelection: [],
        dialogCreateVisible: false,
        dialogEditVisible: false,
        dialogExcelVisible: false,
        formLabelWidth: '128px',
        newEventForm: {
          team_id: '',
          target_id_set: [],
          rule_id: '',
          event_time: '',
          team_id_set: '',
          remark: '',
          point: 0,
          pk_id: this.pk_id
        },
        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'}
          ],
          rule_id: [
            {validator: validateRule, trigger: 'change'}
          ],
          team_id_set: [
            {validator: validateTeam, trigger: 'change'}
          ],
          point: [
            {validator: validateItem, trigger: 'change'}
          ],
          remark: [
            {validator: validateRemark, 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())
              let start = now.getTime() - (now.getDay() - 1) * 24 * 60 * 60 * 1000
              let end = start + 7 * 24 * 60 * 60 * 1000 - 1000
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '上周',
            onClick(picker) {
              const now = new Date(new Date().toLocaleDateString())
              let start = now.getTime() - (now.getDay() + 6) * 24 * 60 * 60 * 1000
              let end = start + 7 * 24 * 60 * 60 * 1000 - 1000
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '本月',
            onClick(picker) {
              const now = new Date()
              let startDate = new Date(now.getFullYear(), now.getMonth(), 1)
              let endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0)
              picker.$emit('pick', [startDate.getTime(), endDate.getTime()])
            }
          }, {
            text: '上月',
            onClick(picker) {
              const now = new Date();
              let startDate = new Date(now.getFullYear() - (now.getMonth() > 0 ? 0 : 1), (now.getMonth() + 11) % 12, 1)
              let endDate = new Date(now.getFullYear(), now.getMonth(), 0)
              picker.$emit('pick', [startDate.getTime(), endDate.getTime()])
            }
          }]
        }
      }
    },
    methods: {
      openCreateDialog() {
        let self = this
        this.newEventForm = {
          target_id_set: [],
          rule_id: '',
          event_time: '',
          team_id_set: '',
          remark: '',
          point: 0,
          remark: '',
          pk_id: this.pk_id
        }

        this.dialogCreateVisible = true
        this.loadTeamListData()
        this.loadAvailableRules()
        this.$nextTick(() => {
          let form = self.$refs['newEventForm']
          form.clearValidate()
        })

      },
      setTeamId() {
        for (let i in this.teamOptions) {
          if (this.teamOptions[i].id == this.newEventForm.team_id_set) {
            this.memberList = this.teamOptions[i].members
            this.newEventForm.target_id_set = []
          }
        }
      },
      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) {
            let 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 () {
        var self = this
        this.$http('get','/api/integral/pk/rules',{
            pk_id: self.pk_id,
            page: 1,
            page_size: 20
          }).then(function (response) {
          if (response.status == 200) {
            let jsonData = response.data.data.list.list
            try {
              self.availableRuleOptions = jsonData
            } catch (err) {
              console.log(err)
            }
          }
        }).catch(function (error) {
          console.log(error)
        })
      },
      //选择积分规则时更新细则列表
      loadAvailableItems: function (formObj, callback) {
        if (!formObj) {
          return;
        }
        let ruleId = formObj.rule_id
        if (isNaN(ruleId) || ruleId < 0) {
          return;
        }
        let 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++) {
          let item = jsonData[index]
          item.checked = false
          item.point = item.value_1
          item.remark = ''
        }
        return jsonData
      },
      applyItemSelection: function (jsonData) {
        let selectedItemIds = this.selectedItems.map(x => x.id)
        for (let index = 0; index < jsonData.length; index++) {
          let item = jsonData[index];
          item.checked = selectedItemIds.indexOf(item.id) > -1
        }
        return jsonData
      },
      generatePointIndication: function (item) {
        let propertyText = item.is_negative == 1 ? '扣除' : '奖励';
        let 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++) {
          let pointType = this.pointTypes[index]
          if (item.point_type == pointType.value) {
            typeText = pointType.label
            break
          }
        }
        return '标准： ' + propertyText + '  ' + valueText + '  ' + typeText
      },
      handleSelectionChange: function (val) {
        this.multipleSelection = val
      },

      resetCreateDialog: function () {
        let 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) {
            let 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 () {
        let 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 {
            return false
          }
        })
      },
      sendCreateRequest() {
        let datenew =  this.$moment(this.newEventForm.event_time).format('YYYY-MM-DD')
        let dataObj = this.newEventForm
        dataObj.event_time = datenew;
        dataObj.log_type = 'employee';
        dataObj.team_id = this.newEventForm.team_id_set;
        dataObj.team_member = this.newEventForm.target_id_set;
        delete dataObj.target_id_set;
        delete dataObj.team_id_set;
        var self = this
        this.$http('post','/api/integral/pk/log',dataObj,
          // headers: {
          //   'Content-Type': 'application/x-www-form-urlencoded'
          // }
        ).then(function (response) {
          let message = ""
          let status = 0
          if (response.status == 200) {
            let data = response.data

            if (data.code == 1) {
              self.$message({
                message: data.msg,
                type: 'success'
              })
              self.$parent.$parent.$parent.loadLogList()
              self.currentPage = 1
              self.dialogCreateVisible = false
              //self.loadEventList()
              //self.resetCreateDialog()
            } else {
              self.$message({
                message: data.msg,
                type: 'error'
              })
            }
          } else {
            self.$message({
              message: '服务器出现问题',
              type: 'error'
            })
          }
        }).catch(function (error) {
          console.log(error)
        })
      },
      sendEditRequest: function () {
        let dataObj = this.eventForm
        if (isNaN(dataObj.point) || !dataObj.point) {
          this.$message({
            message: '请填写积分数值',
            type: 'error'
          });
          this.$refs['pointEditor'].focus()
          return
        }
        let 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) => {
            let paramArray = new Array()
            for (let 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) {
            let 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(() => {
          let targetArr = []
          for (let index in this.multipleSelection) {
            targetArr.push(this.multipleSelection[index].id)
          }
          let 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)
        })
      },


      loadTeamListData() {
        var self = this
        let params =   {
          pk_id: self.pk_id,
          page: 1,
          page_size: 20
        }

        this.$http('get','/api/integral/pk/teams',params).then(function (response) {
          if (response.status == 200) {
            var jsonData = response.data.data.list.list
            try {
              self.teamOptions = jsonData
            } catch (err) {
              console.log(err)
            }
          }
        }).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) {
          let 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) {
        let index = this.selectedItems.map(x => x.id).indexOf(itemId)
        if (!isNaN(index) && index > -1) {
          this.selectedItems.splice(index, 1)
          let itemArray = this.itemSelectForm.items
          for (let i = 0; i < itemArray.length; i++) {
            if (itemArray[i].id == itemId) {
              itemArray[i].checked = false
            }
          }
        }
      }
    },
    created() {
      this.loadTeamListData()
    }
  }
</script>

