<template>
  <a  :class="{'integral-create-review-btn':true}">
    <el-dialog
      append-to-body
      class="integral-create-review-dialog"
      title="适合范围"
      width="1000px"
      top="50px"
      ref="integral_create_review_dialog"
      :visible.sync="dialogCreateVisible"
      :close-on-click-modal="false"
      @open="setDefaultValueForDialog"
    >
      <!-- <el-steps :active="activeIndex" finish-status="success" simple style="margin:10px 22px">
        <el-step title="选择奖扣对象"></el-step>
        <el-step title="选择分类和规则"></el-step>
        <el-step title="提交保存"></el-step>
      </el-steps> -->
      <el-row :gutter="15" style="padding:0px 30px;">
        <el-col :span="24" v-show="activeIndex==0" style="margin-top:10px;">
          <EmployeeSelector ref="EmployeeSelectorComponent" @check="set_target_ids"></EmployeeSelector>
          <!-- removeEmployee -->
        </el-col>
        <el-col
          :span="24"
          v-show="activeIndex==1"
          style="padding-left:0; padding-right:0; margin-top:10px;"
        >
          <el-form
            ref="newEventForm"
            :model="newEventForm"
            :rules="rules"
            @submit.native.prevent
            style="padding:0;"
          >
            <el-row>
              <el-col :span="8" style="padding-left:0;">
                <el-scrollbar
                  wrap-class="column-wrapper scrollable-items-container check-item-box"
                  :native="false"
                  style="height: 450px; margin-right: 10px; border:1px solid #eee; border-bottom:1px solid #eee; border-right:1px solid #eee;"
                >
                  <div style="padding:15px;">
                    <el-tree
                      ref="category_tree_com"
                      highlight-current
                      :default-expand-all="true"
                      :expand-on-click-node="false"
                      :data="categoryTree"
                      @node-click="handleNodeClick"
                    ></el-tree>
                  </div>
                </el-scrollbar>

                <el-form-item label prop="target_id_set" style="display: none;"></el-form-item>
              </el-col>
              <el-col :span="16">
                <div style="padding:8px; padding-top:0;">
                  <el-row :gutter="15" style="padding-right:0;">
                    <el-col :span="12">


                      <el-form-item label prop="rule_id" style="margin-bottom:0;">
                        <el-date-picker
                          v-model="newEventForm.event_time"
                          type="date"
                          value-format="timestamp"
                          placeholder="选择日期"
                          :picker-options="assistantOptions"
                          style="width:100%;"
                        ></el-date-picker>
                      </el-form-item>


                      <el-form-item label prop="event_time" style="margin-bottom:0;" v-if="false">
                        <el-select
                          placeholder="请选择规则"
                          v-model="newEventForm.rule_id"
                          :disabled="!newEventForm.category_id || newEventForm.category_id.length == 0"
                          @change="loadAvailableItems(newEventForm, initializeItemData)"
                          style="width:100%;"
                        >
                          <el-option
                            v-for="(item,idx) in availableRuleOptions"
                            :key="idx"
                            :label="item.name"
                            :value="item.id"
                          ></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12" style="padding-right:0; text-align: right;">
                      <el-button v-if="diy_review == false && newEventForm.category_id.length > 0 && newEventForm.category_id[0] > 0" @click="diy_review = true"
                        type="text">没有匹配的规则？我要自定义录入 >> </el-button>


                      <el-button v-if="diy_review" @click="diy_review = false"
                                 type="text"> <<选择已有规则录入</el-button>

                    </el-col>
                  </el-row>
                </div>
                <el-form-item label prop="category_id" style="display: none;"></el-form-item>
                <el-scrollbar
                  wrap-class="column-wrapper scrollable-items-container check-item-box"
                  :native="false"
                  style="height: 396px;"
                  v-loading="setformloading"
                >
                  <div v-for="(item1, key1) in newEventForm.items">
                    <h3 style="padding-left:15px;">{{item1.name}}</h3>


                    <el-form-item
                      v-for="(item, key) in item1.item_list"
                      :key="key"
                      :prop="'items.' + key1+'.item_list.'+key"
                      :rules="itemRules"
                      style="padding-left:10px;  overflow: hidden; margin-bottom:0;"
                    >
                      <el-tooltip
                        :disabled="diy_review"
                        class="item"
                        effect="dark"
                        :content="item.content"
                        placement="left-start"
                      >
                        <el-card shadow="hover" style="margin-bottom: 15px; padding:0;">
                          <el-checkbox v-if="diy_review == false"
                            style="text-overflow:ellipsis; width:100%; overflow: hidden; line-height: 1; padding:15px;"
                            v-model="item.checked"
                            :label="item.content"
                          ></el-checkbox>
                          <div style="clear:both;"></div>
                          <div style="padding:15px; padding-top:0;" v-show="item.checked">
                          <span v-if="diy_review == false"
                            style="display: block; float: left; line-height: 36px; margin-top:10px;"
                            class="gap-left-8"
                          >{{ generatePointIndication(item) }}</span>







                            <el-select v-if="diy_review" v-model="item.point_type" placeholder="请选择" style=" float:left; margin-right:15px; margin-top:10px; width:73px;">
                              <el-option
                                label="A分"
                                :value="1">
                              </el-option>
                              <el-option
                                label="B分"
                                :value="0">
                              </el-option>

                            </el-select>

                            <el-input-number
                              class="gap-left-8"
                              v-model="item.point"

                              v-show="item.checked && diy_review"
                             style="width:150px; float:left; margin-right:15px; margin-top:10px;"
                            ></el-input-number>

                            <div style="float:right;">
                              <el-button type="text" v-if="diy_review && item1.item_list.length > 1" @click="del_diy_item(key)">移除</el-button>  <el-button type="text" v-if="diy_review" @click="add_diy_item"> 增加一条</el-button></div>
                            <div style="clear: both;"></div>





                            <el-input-number
                              class="gap-left-8"
                              v-model="item.point"
                              :min="item.value_1"
                              :disabled="(item.value_2 == item.value_1 || item.is_range==0)?true:false"
                              :max="item.is_range ? item.value_2 : item.value_1"
                              v-show="item.checked && diy_review == false"
                              style="width:150px; float:right; margin-left:15px; margin-top:10px;"
                            ></el-input-number>
                            <div style="clear:both;"></div>

                            <el-upload
                              :headers="Xtoken"
                              class="avatar-uploader"
                              style="margin-top:10px;"
                              :action="serverdomain+'/integral.php/upload'"
                              :show-file-list="true"
                              multiple
                              :limit="3"
                              :on-exceed="handleExceed"
                              :on-success="(res)=>{ return handleSuccess(res, key, key1)}"
                              :before-upload="beforeFilesUpload"
                              :on-remove="(file)=>{ return handleRemove(file, key, key1)}"
                              :file-list="fileList"
                              :on-preview="onFilePreView"
                              v-model="item.file_list"
                            >
                              <!-- v-model="item.file_list" -->
                              <!-- <span style="margin-right:5px;">图片上传</span> -->
                              <el-button size="mini" type="primary">图片上传</el-button>
                              <span>（选填，最多上传三张）</span>
                            </el-upload>

                            <!-- <div style="display:none;">
                              <img
                                v-for="(item,index) in file_list"
                                :key="index"
                                v-if="(['jpg', 'png', 'bmp', 'jpeg','JPG','PNG']).indexOf(item.name.split('.')[1]) >= 0"
                                :src="serverdomain+item.url"
                                :preview="index"
                                :preview-text="item.name"
                              >
                            </div> -->
                            <el-form-item
                              class="gap-top-8"
                              v-show="item.checked"
                              auto-complete="off"
                              style="margin-top:15px; width:100%;"
                            >
                              <el-input v-model="item.remark" placeholder="备注" type="textarea"></el-input>
                            </el-form-item>
                          </div>
                        </el-card>
                      </el-tooltip>
                    </el-form-item>
                  </div>


                </el-scrollbar>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>

      <el-row :gutter="15" style="margin:0 15px;" v-show="activeIndex == 2">
        <el-col :span="7">
          <el-card class="box-card card-box-item" shadow="never" style="margin-top:15px;">
            <el-scrollbar
              wrap-class="column-wrapper scrollable-items-container check-item-box dept_tree"
              :native="false"
              style="height: 350px;"
            >
              <div style="padding-right:15px;">
                <el-table
                  :data="target_list"
                  :border="false"
                  tooltip-effect="dark"
                  style="width: 100%"
                >
                  <el-table-column prop="name" :label="'已选择人员（'+(target_list.length)+'人）'">
                    <template slot-scope="scope">
                      <div class="rank_head" style="cursor: pointer;">
                        <img
                          v-if="scope.row.img_url != null"
                          v-bind:src="scope.row.img_url"
                          width="42px"
                          height="42px"
                        >
                        <img
                          v-if="scope.row.img_url == null"
                          src="static/images/head_default.png"
                          width="42px"
                          height="42px"
                        >
                        {{scope.row.name}}
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-scrollbar>
          </el-card>
        </el-col>
        <el-col :span="17" style="margin-top: 15px;">
          <div>
            <span style="margin-right:5px; color: #000">多人审批</span>
            <el-select
              v-model="reviewer_other_ids"
              filterable
              multiple
              :multiple-limit="5"
              placeholder="选填"
              class="gap-right-8"
              style="width:380px;"
            >
              <el-option
                v-for="(reviewItem,idx) of employerList"
                :key="idx"
                :label="reviewItem.name"
                :disabled="newEventForm.target_id_set.indexOf(reviewItem.id) >=0"
                :value="reviewItem.id"
              ></el-option>
            </el-select>
          </div>

          <!-- </el-form-item> -->


          <div v-for="(item1, key1) in newEventForm.items">

          <el-card
            v-for="(item,index) in item1.item_list"
            :key="index"
            v-if="item.checked"
            class="box-card card-box-item"
            shadow="hover"
            style="margin-top:15px; padding:0"
          >
            <p>{{item.content}}</p>
            <p>备注：{{item.remark}}</p>
            <!-- <p>???{{item}}</p> -->
            <p v-if="item.is_negative == 0 || (item.point > 0 && diy_review)">奖分：
              <el-tag>{{item.point}}</el-tag>
              <span>{{item.point_type === 0?'B分':'A分'}}</span>
            </p>

            <p v-if="item.is_negative == 1 || (item.point < 0 && diy_review)">扣分：
              <el-tag type="danger">{{item.point}}</el-tag>
              <span>{{item.point_type === 0?'B分':'A分'}}</span>
            </p>
          </el-card>
          </div>
        </el-col>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelHandle">取 消</el-button>
        <el-button @click="activeIndexPrev" v-show="activeIndex > 0">上一步</el-button>
        <el-button @click="activeIndexNext" type="primary" v-show="activeIndex < 2">下一步</el-button>

        <el-button
          v-show="activeIndex == 2"
          :loading="submitLoading"
          type="primary"
          @click="submitCreateForm('newEventForm')"
        >提 交</el-button>
      </div>
    </el-dialog>
<!-- 
    <div class="card-panel" v-if="btn_type==0">
      <div class="tpzs3"></div>
      <div class="card-panel-description">
        <div class="card-panel-text">积分录入</div>
        <div class="card-panel-text2">按规则进行奖扣</div>
      </div>
    </div> -->
        <div style="display:none;">
          <img
            v-for="(item,index) in file_list"
            :key="index"
            v-if="(['jpg', 'png', 'bmp', 'jpeg','JPG','PNG']).indexOf(item.name.split('.')[1]) >= 0"
            :src="serverdomain+item.url"
            :preview="index"
            :preview-text="item.name"
          >
        </div>
  </a>
</template>
<script>
import EmployeeSelector from '@/views/integral/EmployeeSelector'
import { getToken } from '@/utils/auth'
import Vue from 'vue'
import preview from 'vue-photo-preview'
import 'vue-photo-preview/dist/skin.css'
Vue.use(preview, {
  tapToClose: false
})
export default {
  components: { EmployeeSelector },
  props: {
    iShow: {
      type: Boolean,
      default: false
    }
  },
  name: 'IntegralCreateReviewBtn',
  watch: {
   iShow(val) {
       this.dialogCreateVisible = val;
   }
  },
  data() {
    const validateTarget = (rule, value, callback) => {
      if (!value || value.length == 0) {
        this.$message({
          message: '请选择奖扣积分对象',
          type: 'error'
        })

        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) && value.checked == true) {
        return callback(new Error('请填写有效的积分数值'))
      }
      callback()
    }
    return {
      diy_review: false,
      Xtoken: { 'X-Token': getToken() },
      fileList: [],
      file_list: [],
      reviewer_other_ids: [],
      employerList: [],
      setformloading: false,
      submitLoading: false,
      activeIndex: 0,
      dialogWidth: '510px',
      dialogWidth_left: 16,
      dialogWidth_right: 0,
      dialogWidth_employee: 8,
      profile: this.$store.getters.user_info,
      totalCount: 0,
      tableData: null,
      currentPage: 1,
      multipleSelection: [],
      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
        }
      },
      target_list: [],
      itemSelectForm: {
        target_id_set: [],
        category_id: [],
        rule_id: '',
        event_time: '',
        items: [],
        get_category: 1
      },
      selectedItems: [],
      rules: {
        target_id_set: [{ validator: validateTarget, trigger: 'blur' }],
        category_id: [{ validator: validateCategory, trigger: 'blur' }]
        // rule_id: [{ validator: validateRule, trigger: 'v' }]
      },
      itemRules: {
        validator: validateItem,
        trigger: 'blur'
      },
      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()])
            }
          }
        ]
      }
    }
  },
  methods: {
    add_diy_item() {
      this.newEventForm.items[0].item_list.push({ 'is_add': 0, 'remark': '', 'id': 0, 'content': '', 'rule_id': 0, 'is_range': 1, 'point_type': 0, 'point': 1, checked: true, file_list: [] })
    },

    del_diy_item(key) {
      this.newEventForm.items[0].item_list.splice(key, 1)
    },

    onFilePreView(file) {
      // 点击时查看图片
      const $ext_list1 = ['jpg', 'png', 'bmp', 'jpeg','JPG','PNG']  
      const $ext_name1 = file.name.split('.')[1]
      if ($ext_list1.indexOf($ext_name1) >= 0) {
        // console.log(this.serverdomain + file.response.url)
        let ii = 0
        for (const i in this.file_list) {
          console.log(this.file_list[i].name)
          if (
            ['jpg', 'png', 'bmp', 'jpeg','JPG','PNG'].indexOf(
              this.file_list[i].name.split('.')[1]
            ) >= 0
          ) {
            if (this.file_list[i].name == file.response.file_name) {
              // console.log(ii)
              this.openPhotoSwipe(
                ii,
                document.querySelectorAll('img[preview]')
              )
              return
            }
            ii++
          }
        }
      }
    },
    handleRemove(file, id) {
      let delIndex = -1
      this.file_list.forEach((item, idx) => {
        if (item.url === file.response.url && id === item.index) {
          delIndex = idx
          return false
        }
      })
      this.file_list.splice(delIndex, 1)
    },
    beforeFilesUpload(file) {
      const $ext_list = ['jpg', 'png', 'bmp', 'jpeg','JPG','PNG']
      const $ext_name = file.name.split('.')[1]
      if ($ext_list.indexOf($ext_name) === -1) {
        this.$message.warning('不支持的文件格式')
        return false
      }
    },
    handleSuccess(res, ids, key1) {
      console.log('res--------??11111111')

      this.newEventForm.items[key1].item_list[ids].file_list.push({ url: res.url, name: res.file_name })
      console.log(this.newEventForm)
      // this.file_list.push({index: ids, url: res.url, name: res.file_name })
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    activeIndexNext() {
      const self = this
      if (
        this.activeIndex == 0 &&
        self.newEventForm.target_id_set.length == 0
      ) {
        this.$message({
          message: '请选择奖扣积分对象',
          type: 'error'
        })
        return false
      }

      if (this.activeIndex == 1 && this.diy_review) {
        for (const i in self.newEventForm.items[0].item_list) {
          if (self.newEventForm.items[0].item_list[i].remark == '') {
            this.$message({
              message: '请填写完整的事件备注',
              type: 'error'
            })
            return false
          }

          if (self.newEventForm.category_id <= 0) {
            this.$message({
              message: '请选择积分分类',
              type: 'error'
            })
            return false
          }
        }
      }

      if (this.activeIndex == 1) {
        if (self.newEventForm.category_id <= 0) {
          this.$message({
            message: '请选择积分分类',
            type: 'error'
          })
          return false
        }
      }

      if (this.activeIndex == 1) {
        /* if (self.newEventForm.rule_id == '') {
          this.$message({
            message: '请选择积分规则',
            type: 'error'
            // customClass:'msgCustomClass'
          })
          return false
        }*/

        let checked = 0
        for (const j in this.newEventForm.items) {
          for (const i in this.newEventForm.items[j].item_list) {
            if (this.newEventForm.items[j].item_list[i].checked) {
              checked++
            }
          }
        }

        if (checked == 0) {
          this.$message({
            message: '没有选中积分细则',
            type: 'error'
          })

          return false
        }
      }

      this.activeIndex++
    },
    activeIndexPrev() {
      this.activeIndex--
    },
    dateFormatter: function(row, column, cellValue) {
      return this.$moment(cellValue * 1000).format('YYYY年MM月DD日')
    },

    // employee_checked(dd){console.log(dd,'dfasdfa')},
    set_target_ids(data) {
      const self = this
      self.newEventForm.target_id_set = []
      for (const i in data) {
        self.newEventForm.target_id_set.push(data[i].id)
      }
      self.target_list = data
    },

    handleNodeClick(data) {
      this.newEventForm.category_id = [data.value]
      this.loadAvailableRules(this.newEventForm)
    },

    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 (this.diy_review) {
        return
      }
      this.setformloading = true
      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) {
          self.setformloading = false
          if (response.status == 200) {
            const jsonData = response.data
            try {
              self.availableRuleOptions = jsonData
              formObj.rule_id = ''
              formObj.items = []

              self.loadAvailableItems(formObj, self.initializeItemData)
            } catch (err) {
              console.log(err)
            }
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    // 选择积分规则时更新细则列表
    loadAvailableItems: function(formObj, callback) {
      const self = this
      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
      }
      const categoryPath = formObj.category_id
      if (!categoryPath || categoryPath.length == 0) {
        return
      }
      params.category_id = categoryPath[categoryPath.length - 1]
      this.$http('get','/integral.php/ajax_request_common/get_integral_items_by_category_id', params)
        .then(function(response) {
          if (response.status == 200) {
            let jsonData = response.data
            try {
              if (callback) {
                jsonData = callback.call(null, jsonData)
              }
              formObj.items = jsonData
              // 新增
              formObj.items.forEach(item => {
                for (const i in item.item_list) {
                  item.item_list[i].file_list = []
                }
              })
            } catch (err) {
              console.log(err)
            }
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    initializeItemData: function(jsonData) {
      for (let index1 = 0; index1 < jsonData.length; index1++) {
        for (let index = 0; index < jsonData[index1].item_list.length; index++) {
          const item = jsonData[index1].item_list[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
    },

    resetCreateDialog: function() {
      this.newEventForm.rule_id = ''
      this.newEventForm.items = []
      if (this.diy_review) {
        this.newEventForm.items = [{ 'id': 0, 'name': '', 'item_list': [{ 'is_add': 0, 'remark': '', 'id': 0, 'content': '', 'rule_id': 0, 'is_range': 1, 'point_type': 0, 'point': 1, checked: true, file_list: [] }] }]
      }
      this.dialogWidth = '510px'

      // this.newEventForm.category_id = []
      this.newEventForm.rule_id = ''
      // this.newEventForm.event_time = ''
      // this.newEventForm.items = []

      this.file_list = []

      const form = this.$refs['newEventForm']
      form.clearValidate()

      // this.activeIndex = 0;
    },
    cancelHandle() {
    //   this.dialogCreateVisible = false
    this.resetCreateDialog()
    this.$emit("changeShow");
    //   this.activeIndex = 0
      // this.$refs.EmployeeSelectorComponent.
    },
    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,e) => {
        if (valid) {
          if (form) {
            self.sendCreateRequest()
          }
        } else {

          console.log('验证未通过')
          return false
        }
      })
    },
    sendCreateRequest: function() {
      const dataObj = JSON.parse(JSON.stringify(this.newEventForm))

      console.log(dataObj, 11111111)

      const formData = {}
      const emptyItems = []
      const items = []

      console.log('926')
      for (const item in dataObj) {
        if (item == 'category_id') {
          formData['category_id'] = dataObj[item]
          continue
        }
        if (item == 'items') {
          // for(let item1 in dataObj[item].item_list){

          console.log(dataObj[item])
          for (const item1 in dataObj[item]) {
            const checkedRuleItems = dataObj[item][item1].item_list.filter(x => x.checked)
            if (checkedRuleItems && checkedRuleItems.length > 0) {
              emptyItems.push(true)
            }

            this.file_list.forEach(fileItem => {
              checkedRuleItems.forEach((innerItem, idx) => {
                if (fileItem.index === idx) {
                  console.log(innerItem)
                  // innerItem.file_list.push({ name: fileItem.name, url: fileItem.url })
                }
              })
            })
            for (const i in checkedRuleItems) {
              checkedRuleItems[i]['content'] = checkedRuleItems[i].remark

              items.push(checkedRuleItems[i])
            }
          }
          for(let i in items){
            items[i]['category_id'] = dataObj['category_id'][dataObj['category_id'].length - 1]
          }
          formData[item] = JSON.stringify(items)


          // }
          console.log('967')
        } 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.length == 0) {
        this.$message({
          message: '没有选中积分细则',
          type: 'error'
        })
        return
      }
      formData['recorder_id'] = this.profile.id
      formData['reviewer_other_ids'] = this.reviewer_other_ids
      var self = this
      self.submitLoading = true
      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) {
          self.submitLoading = false
          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 = data.info
                break
              case -1:
                message = '表单参数错误'
                break
              default:
                message = data.info ? data.info : '积分事件录入失败'
            }
          } else {
            message = '服务器出现问题'
          }
          if (status == 1) {
            let content = ''
            response.data.results.forEach((item, idx) => {
              if (item.point > 0) {
                content += `<div style="color: #606266; font-size: 16px; margin-left: 20px;">${idx +
                  1}.${item.employee.name} 奖励${item.point} ${
                  item.point_type
                } ${item.info}</div>`
              } else {
                const score = parseInt(item.point)
                content += `<div style="color: #606266; font-size: 16px; margin-left: 20px;">${idx +
                  1}.${item.employee.name} 扣除${score} ${
                  item.point_type
                } ${item.info}</div>`
              }
            })
            content += `<div style="margin-top:20px;">可在数据统计→<a style="color:#689bff" href="/#/event_manage" target="_blank">积分事件中查看哦</a></div>`
            self
              .$confirm(content, response.data.info, {
                dangerouslyUseHTMLString: true,
                confirmButtonText: '继续录入',
                cancelButtonText: '不录入了',
                showClose: false
              }).then(() => {
                self.activeIndex = 0
              })
              .catch(() => {
                self.dialogCreateVisible = false
              })
          } else {
            self.$message({
              message: message,
              type: 'error'
            })
          }
          if (status == 1) {
            // self.dialogCreateVisible = false
            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
      }
      const 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)
        })
    },
    // 获取管理者列表
    loadEmployerList: function() {
      var self = this
      this.$http('get','/integral.php/ajax_request_common/prepare_integral_options',{
            id: this.profile.id,
            superior_list: 1
          })
        .then(function(response) {
          if (response.status == 200) {
            var jsonData = response.data
            try {
              self.employerList = jsonData.reviewer_list
            } 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
          }
        }
      }
    }
  },
  created() {
    this.loadWidgetData()
    this.loadTargetRange()
    this.loadEmployerList()
    this.loadPointType()
  }
}
</script>

<style>
.msgCustomClass{
  top: 50%;
  margin-top: -23px;
}
.integral-create-review-btn .tpzs3 {
  margin: 0 auto;
  width: 40px;
  height: 40px;
  background-image: url(/images/jflr.png);
  background-size: 100%;
}
.integral-create-review-btn .card-panel-description {
  width: 100%;
  text-align: center;
  color: #666;
}
.integral-create-review-btn .card-panel-text {
  line-height: 40px;
  font-size: 20px;
  font-weight: bold;
}

.integral-create-review-btn .card-panel-text2 {
  font-size: 14px;
  line-height: 20px;
  color: rgba(102, 102, 102, 1);
}
.check-item-box .el-card__body {
  padding: 0;
  line-height: 1;
}
.integral-create-review-dialog .el-dialog__header {
  display: none;
}
.integral-create-review-dialog .el-dialog__body {
  padding-bottom: 0;
}
.integral-create-review-dialog .card-box-item .el-card__body {
  padding: 5px 15px;
}
</style>
