<template>
  <a class="integral-create-review-btn">
    <el-button  @click="dialogCreateVisible = true" type="primary" plain>创建规则</el-button>
    <el-button  @click="openDialog = true" type="primary" plain>高级设置</el-button>
    <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 @check="set_target_ids"></EmployeeSelector>
        </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="event_time" style="margin-bottom:0;">
                        <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 in availableRuleOptions"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                          ></el-option>
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12" style="padding-right:0;">
                      <el-form-item label prop="rule_id" style="margin-bottom:0;">
                        <el-select
                          v-model="newEventForm.query_time"
                          placeholder="自动执行周期"
                          style="width:100%;"
                        >
                          <el-option key="0" label="每天" value="0"></el-option>
                          <el-option key="2" label="每月" value="2"></el-option>
                        </el-select>
                      </el-form-item>
                    </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"
                >
                  <el-form-item
                    v-for="(item, key) in newEventForm.items"
                    :key="item.id"
                    :prop="'items.' + key"
                    :rules="itemRules"
                    style="padding-left:10px;  overflow: hidden; margin-bottom:0;"
                  >
                    <el-tooltip
                      class="item"
                      effect="dark"
                      :content="item.content"
                      placement="left-start"
                    >
                      <el-card shadow="hover" style="margin-bottom: 15px; padding:0;">
                        <el-checkbox
                          :disabled="item.is_range==1"
                          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="false">
                          <span
                            style="display: block; float: left; line-height: 36px; margin-top:10px;"
                            class="gap-left-8"
                          >{{ generatePointIndication(item) }}</span>
                          <el-input-number
                            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="width:150px; float:right; margin-left:15px; margin-top:10px;"
                          ></el-input-number>
                          <div style="clear:both;"></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>
                </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">
          <el-card
            v-for="(item,index) in newEventForm.items"
            :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 v-if="item.is_negative == 0">奖分：
              <el-tag>{{item.point}}</el-tag>
            </p>

            <p v-if="item.is_negative == 1">扣分：
              <el-tag type="danger">{{item.point}}</el-tag>
            </p>
          </el-card>
        </el-col>
      </el-row>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCreateVisible = false">取 消</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>
    <!-- 高级设置弹窗 -->

      <el-dialog
        append-to-body
        title="高级设置"
        width="700px"
        top="50px"
        ref="openChange"
        custom-class="setClass"
        :visible.sync="openDialog"
        :close-on-click-modal="false"
         @open="getOpenChange()"
      >
      <div style="width: 380px;font-size: 12px;color:#909399;margin-bottom: 28px;line-height: 17px;">

          <p style="margin-bottom: 0px;">勾选后，自动加分与考勤挂钩，按实际出勤天数计算加分</p>
           <p  style="margin-top: 5px;">计算方式：月实际加分=月初始加分*（月实际出勤天数/月应出勤天数）</p>
      </div>
      <el-scrollbar
          wrap-class="column-wrapper scrollable-items-container check-item-box dept_tree"
          :native="false"
          style="height: 500px;">
       <div v-for="(item, i) in rule_list" :key="i" @click="handleClick(item.items)"  >
         <div style="color:#606266;font-size: 16px;">{{item.rule_name}}</div>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="checkedCities" style="padding-bottom:15px;" @change="handleCheckedCitiesChange">
            <el-checkbox style="padding-left: 16px;padding-bottom: 10px;" v-for="item in item.items" :key="item.id" :label="item.id">{{item.content}}</el-checkbox>
         </el-checkbox-group>
            <div v-if="rule_list.length-1 != i" style="width: 608px;border-top: 1px solid #E7E6EB;margin: 20px auto;"></div>
        </div>
      </el-scrollbar>

         <el-button style="margin: 40px 0 0 210px;" @click="openDialog=false"> 取消</el-button>
        <el-button  style="margin: 40px 0 0 10px;"  type="primary" @click="saveBook"> 保存</el-button>
    </el-dialog>
  </a>
</template>
<script>
import EmployeeSelector from "@/views/integral/EmployeeSelector";
import { getToken } from "@/utils/auth";
export default {
  components: { EmployeeSelector },
  name: "IntegralCreateReviewBtn",
  data() {
    let validateTarget = (rule, value, callback) => {
      if (!value || value.length == 0) {
        this.$message({
          message: "请选择奖扣积分对象",
          type: "error"
        });

        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.point) || parseInt(value.point) == 0) {
        return callback(new Error("请填写有效的积分数值"));
      }
      callback();
    };
    return {
      checkItems:[],
      rule_list:[],
      isIndeterBook:false,
      citiesExactly:[],
      openDialog: false, // 高级设置弹窗
      checkAll: false,
      checkedCities: [], // 学历选中后数组
      cities: ["北京", "上海", "杭州"], // 学历循环数组
      checkBook: [], // 职务循环
      certificate: [], // 选中职务循环
      isIndeterminate: true,
      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: {
        query_time: "",
        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: [],
      sendArray:[],
      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: {
    handleClick(item) {
      this.checkItems = item;
    },
    // 全选
    // handleCheckAllChange(val) {
    //   console.log(val)
    //   this.isIndeterminate = false;
    //   let array = [];
    //   for(var i = 0; i < this.checkItems.length; i ++) {
    //     array.push( this.checkItems[i].id);

    //   }
    //   this.checkedCities = val ? array : [];
    // },
    // 选中
    handleCheckedCitiesChange(value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount ===  this.checkItems.length;

        this.isIndeterminate = checkedCount > 0 && checkedCount <  this.checkItems.length;
    },
    // 保存设置
    saveBook() {
      const self = this;
      let NoCheckList = self.rule_list;
       let data = [];
       let is_attendance = 1;
       let newArray = [];

      for(var item in NoCheckList) {
       for(var i = 0; i<NoCheckList[item].items.length; i ++) {
         newArray.push(NoCheckList[item].items[i].id)
       }
      }
      let spliceArray =  newArray.filter(i=> self.checkedCities.indexOf(i) == -1)
        var array =[];
        for(var i = 0; i<spliceArray.length; i++ ) {
          let id = spliceArray[i];
          let is_attendance = 0;
           array.push({id,is_attendance});
       }

       let dataArray = [];
        for(var i = 0; i< self.checkedCities.length; i++ ) {
          let id =  self.checkedCities[i];
           data.push({id,is_attendance});
       }
       dataArray = array.concat(data);
       self.sendArray = dataArray;


       this.$http('post',"/integral.php/employee_attendance/attendance_fixed_submit",{data: self.sendArray})
        .then(function(response) {
          if (response.status == 200 && response.data.code == 1000) {
               self.$message({
                  message: "设置成功",
                  type: "success"
                });
                  self.openDialog = false;
            try {

            } catch (err) {
              console.log(err);
            }
          }else {
            self.$message({
                  message: response.data.msg,
                  type: "error"
                });
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    // 获取高级设置里面的数据
    getOpenChange() {
      this.checkedCities = [];
       const self = this;
       this.$http('post',"/integral.php/employee_attendance/checked_items")
        .then(function(response) {
          if (response.status == 200) {
              let { data={} } = response.data;
              let newArray = [];
              self.rule_list = data.rule_list;
              for(var item in data.rule_list) {
              for(var i = 0; i<data.rule_list[item].items.length; i ++) {
                if(data.rule_list[item].items[i].is_attendance == 1) {
                   let id = data.rule_list[item].items[i].id;
                   self.checkedCities.push(id);

                }
              }
            }
              console.log(self.checkedCities)

            try {

            } catch (err) {
              console.log(err);
            }
          }
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    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) {
        if (self.newEventForm.rule_id == "") {
          this.$message({
            message: "请选择积分规则",
            type: "error"
          });
          return false;
        }

        let checked = 0;
        for (let i in this.newEventForm.items) {
          if (this.newEventForm.items[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 (let 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) {
            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(formObj) {
      this.setformloading = true;
      if (!formObj) {
        return;
      }
      let 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],type: 1})
        .then(function(response) {
          self.setformloading = false;
          if (response.status == 200) {
            let 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) {
      const self = this;
      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() {
      this.newEventForm.rule_id = "";
      this.newEventForm.items = [];
      this.dialogWidth = "510px";

      this.newEventForm.category_id = [];
      this.newEventForm.rule_id = "";
      this.newEventForm.event_time = "";
      this.newEventForm.items = [];

      let form = this.$refs["newEventForm"];
      form.clearValidate();

      this.activeIndex = 0;
    },
    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 {
          //console.log('验证未通过');
          return false;
        }
      });
    },
    sendCreateRequest: function() {
      let dataObj = this.newEventForm;
      let formData = {};
      let emptyItems = false;
      for (let item in dataObj) {
        if (item == "category_id") {
          continue;
        }
        if (item == "items") {
          let 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;
      self.submitLoading = true;
      this.$http("post","/integral.php/point_auto_setting/add",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) {
          self.submitLoading = false;
          let message = "";
          let status = 0;
          if (response.status == 200) {
            self.$emit("send_success", response);

            let data = response.data;
            status = isNaN(data.code) ? 0 : parseInt(data.code);
            switch (status) {
              case 1:
                message =
                  "操作完成，成功设置" +
                  data.data.ret.length +
                  "条记录，" +
                  data.data.ex +
                  "条记录已经存在";
                break;
              case -1:
                message = "表单参数错误";
                break;
              default:
                message = data.info
                  ? data.info
                  : "操作失败，" + data.data.ex + "条记录已经存在";
            }
          } else {
            message = "服务器出现问题";
          }
          self.$message({
            message: message,
            type: status == 1 ? "success" : "error"
          });
          if (status == 1) {
            //self.dialogCreateVisible = false
            self.resetCreateDialog();
          }
        })
        .catch(function(error) {
          self.submitLoading = false;
          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);
        });
    },
    //获取控件所需数据
    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.loadWidgetData();
    this.loadTargetRange();
  }
};
</script>

<style scoped>
.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;
}
/deep/ .setClass .el-dialog__body {
  padding-left: 25px;
  padding-top: 0px;
}
</style>
