<template>
  <div>
    <!-- 头部提示 -->
    <el-alert class="diy-tip" title="如何使用积分规则?" type="success" @close="tips_close" v-show="tips_show" description show-icon>
      <p>先【添加规则分类】，再【添加规则】;或者直接【导入规则】</p>
    </el-alert>

    <!-- 中间内容 -->
    <el-row class="display-flex" v-loading="dept_loading">
      <el-col :span="6" class="rule_class_box">
        <div class="padding24">
          <el-button class="btn-block" @click="add_class" type="primary">+ 添加规则分类</el-button>
          <el-tree v-show="dept_list !== null && dept_list.length != 0" :data="dept_list" :props="defaultProps"
            @node-click="dept_click" :expand-on-click-node="false" :highlight-current="true" class="cate-tree"></el-tree>
          <div v-show="!dept_loading && dept_list !== null && dept_list.length == 0" class="" style="margin-top: 100px;">
            <div style="padding: 0 10px">
              <img src="static/images/nodata_default.png" width="100%" alt="">
            </div>
            <div style="text-align: center; line-height:34px">还没有规则分类</div>
            <div style="text-align: center; color: #26A2FF;" @click="add_class">添加规则分类</div>
          </div>
        </div>
      </el-col>
      <el-col :span="18" class="border-right">
        <div class="padding24">
          <h2><pre style="font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, Arial, sans-serif;">{{dept_name}}<el-button style="margin-left: 10px" v-show="show_edit_btn" @click="edit_class">编辑</el-button></pre>
          </h2>
          <div style="margin-top:2px; margin-bottom:15px;" class="inline-block-btn-list">
            <el-button
              type="danger"
              plain
              @click="del_item"
            >批量删除</el-button>
            <el-button
              type="primary"
              @click="add_rule"
            >添加规则</el-button>
            <el-button
              type="primary"
              plain
              @click="theImportRules"
            >导入规则</el-button>
<!--            <el-button
              type="primary"
              plain
              @click="derivedRule"
            >导出规则</el-button> -->
            <div class="gap-right-8 fr" style="display:inline-block; width:180px;">
              <el-input
                placeholder="搜索规则内容"
                ref="search-bar"
                v-model="keyword"
                class="input-with-select"
                @keyup.enter.native="onFilterChanged"
              >
                <el-button slot="append" icon="el-icon-search" @click="onFilterChanged"></el-button>
              </el-input>
            </div>
          </div>
          <el-table stripe ref="multipleTable" :data="list" tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange"
            @row-click="editDetails" class="rule_category_box">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column prop="remark" label="内容" width="500" style="padding-right:30px;"></el-table-column>
            <el-table-column label="分值">
              <template slot-scope="scope">
                <div v-if="scope.row.range_type == 1"><span :class="scope.row.min_point > 0?'color_green':'color_red'"> {{scope.row.min_point}} </span> {{types_list[scope.row.pt_id]}} </div>
                <div v-if="scope.row.range_type == 2"><span :class="scope.row.min_point > 0?'color_green':'color_red'"> {{scope.row.min_point}} </span> 至 <span :class="scope.row.max_point > 0?'color_green':'color_red'"> {{scope.row.max_point}} </span> {{types_list[scope.row.pt_id]}} </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>
    <!-- 编辑添加分类 -->
    <el-dialog :title="class_type=='add'?'添加规则分类':'编辑规则分类'" @close="add_dept_close('dept_formdata')" :visible.sync="class_show" :close-on-click-modal="false"
      width="500px">
      <el-form :model="dept_formdata" ref="dept_formdata" :rules="dept_formdata_rules" label-width="80px">
        <el-form-item label="规则分类" prop="name">
          <el-input v-model="dept_formdata.name"></el-input>
        </el-form-item>
        <el-form-item label="上级分类">
          <el-cascader v-model="dept_formdata.pid" :options="dept_list" :props="{ checkStrictly: true, label: 'name', value: 'id', children: 'child'}"  @change="cascader_closeSJ" ref="cascaderHandleSJ"
            clearable></el-cascader>
        </el-form-item>
        <el-form-item style="text-align: right; margin-bottom:0;">
          <el-button type="danger" @click="del_dept" v-show="class_type=='edit'">删除分类</el-button>
          <el-button @click="add_dept_close('dept_formdata')">取消</el-button>
          <el-button type="primary" @click="submit_add_dept('dept_formdata')">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 添加编辑规则 -->
    <el-dialog :title="rule_type=='add'?'添加规则':'编辑规则'" :visible.sync="rule_show" @close="rule_close('rules_detail_form')" :close-on-click-modal="false"
      width="700px">
      <el-form :model="rules_detail_form" ref="rules_detail_form" :rules="rules" label-width="80px">
        <el-form-item label="规则内容" prop="remark">
          <el-input v-model="rules_detail_form.remark" placeholder="请输入规则内容" type="textarea" :rows="3"></el-input>
        </el-form-item>

        <el-form-item label="所属分类" prop="rule_id">
          <div style="position: relative;">
            <div style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; z-index: 9;" @click="not_data"
              v-show="dept_list !==null && dept_list.length == 0"></div>
              
          <el-cascader placeholder="请选择分类" v-model="rules_detail_form.rule_id" :options="dept_list" :props="{ checkStrictly: true, label: 'name', value: 'id', children: 'child'}"  @change="cascader_close" ref="cascaderHandle"
            clearable></el-cascader>

            <!-- <el-cascader placeholder="请选择分类" v-model="rules_detail_form.rule_id" @visible-change="select_rule" @change="cascader_close"
              :options="dept_list" ref="cascaderHandle" :props="{ checkStrictly: true, label: 'name', value: 'id', children: 'child'}"></el-cascader> -->
          </div>
        </el-form-item>
        <el-form-item label="规则类型" prop="pt_id">
          <el-radio v-model="rules_detail_form.pt_id" :label="item.id" v-for="(item,index) in point_types" :key="index"
            v-show="item.name !== '绩效分'">{{item.name}}</el-radio>
        </el-form-item>
        <el-form-item label="规则积分" prop="range_type">
          <el-radio-group v-model="rules_detail_form.range_type">
            <el-radio :label="item.value" v-for="(item,index) in range_type_arr" :key="index">{{item.name}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-row :gutter="20" class="select_width">
            <el-col :span="11">
              <el-input placeholder="请输入分值" :rules="[{ required: true, message: '请输入加分项名称', trigger: 'blur' }]"
                v-model="rules_detail_form.min_point" type="Number" class="input-with-select">
                <el-select v-model="integral_select_name1" slot="prepend" placeholder="请选择类型">
                  <el-option v-for="(item,index) in integral_select" :key="index" :label="item.name" :value="item.value"></el-option>
                </el-select>
              </el-input>
            </el-col>
            <el-col :span="2" v-show="rules_detail_form.range_type == 2">至</el-col>
            <el-col :span="11" v-show="rules_detail_form.range_type == 2">
              <el-input placeholder="请输入分值" :rules="[{ required: true, message: '请输入加分项名称', trigger: 'blur' }]"
                v-model="rules_detail_form.max_point" type="Number" class="input-with-select">
                <el-select v-model="integral_select_name2" slot="prepend" placeholder="请选择类型">
                  <el-option v-for="(item,index) in integral_select" :key="index" :label="item.name" :value="item.value"></el-option>
                </el-select>
              </el-input>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item style="text-align: right; margin-bottom:0;">
          <el-button type="danger" @click="del_rule" v-show="rule_type=='edit'">删除规则</el-button>
          <el-button @click="rule_close('rules_detail_form')">取消</el-button>
          <el-button type="primary" v-show="rule_type == 'add'" @click="add_submit_rule('rules_detail_form')">确定</el-button>
          <el-button type="primary" v-show="rule_type == 'edit'" @click="edit_submit_rule('rules_detail_form')">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 导入规则 -->
    <el-dialog
      title="导入规则"
      :visible.sync="import_rules_show"
      width="500px"
      @before-close="close_import">
      <el-row>
        <el-col :span="12">
          <div class="text-center">
            <p>1、下载规则模版，填写好规则</p>
            <p>
              <img src="static/images/rules_mould.png" alt="">
            </p>
            <p>规则表</p>
            <p><a target="_blank" :href="publicBASE_API+'/api/download/rule_item'" ><el-button type="primary">下载模板</el-button></a></p>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="text-center">
            <p>2、上传填好的规则表</p>
            <p>
              <img src="static/images/rules_mould1.png" alt="">
            </p>
            <p>仅支持xls、xlsx格式文件</p>
          <el-upload
              class="upload-demo"
              :headers="ATOKEN"
              :data="{type:'rule_item'}"
              ref="upload"
              :limit = '1'
              :action="integralUpload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :before-upload="beforeFilesUpload"
              :file-list="fileList">
              <el-button slot="trigger" type="primary">选取文件</el-button>
            </el-upload>
            <p><el-button type="primary" @click="submitUpload" :loading="save_loading" v-show="import_btn_show" block>导入</el-button></p>
          </div>
        </el-col>
      </el-row>
    </el-dialog>

    <el-dialog
      title="导入结果"
      :visible.sync="error_list_show"
      @close='error_list_SX'
      :append-to-body='true'
      width="700px">
      <el-table :data="error_list">
        <el-table-column prop="line" label="行数">
          <template slot-scope="scope">
            <div>第{{scope.row.line}}行</div>
          </template>
        </el-table-column>
        <el-table-column prop="errors" label="备注信息"></el-table-column>
      </el-table>
    </el-dialog>

  </div>
</template>

<script>
  import { getToken } from '@/utils/auth'
  import Vue from 'vue'
  let PerformTheNumber = true;//五秒执行一次变量
  export default {
    name: "rule_category",
    data() {
      return {
        integralUpload:process.env.BASE_API + '/api/upload/excel',
        publicBASE_API:process.env.BASE_API,
        error_list_show:false,
        error_list: [],

        keyword:'',//搜索关键字
        ATOKEN: { 'A-TOKEN': getToken()},
        show_edit_btn: false,
        class_show: false,
        dept_formdata_rules: {
          name: [{
              required: true,
              message: '请输入规则分类',
              trigger: 'blur'
            },
            {
              min: 2,
              max: 10,
              message: '长度在 2 到 10 个字符',
              trigger: 'blur'
            }
          ],
        },
        class_type: 'add',
        class_item: {},
        del_item_id: [],
        rule_show: false,
        rules_detail_form: {
          rule_id: '',
          range_type: '1',
          prize_type: '0',
          min_point: '',
          max_point: '',
          remark: '',
          is_attendance: '0',
          cycle_type: '1',
          pt_id: 2
        },
        rule_type: 'add',
        rules: {
          remark: [{
              required: true,
              message: '请输入规则内容',
              trigger: 'blur'
            },
            {
              max: 300,
              message: '规则内容请控制在300字以内',
              trigger: 'blur'
            },
          ],
          rule_id: [{
            required: true,
            message: '请选择分类',
            trigger: 'blur'
          }, ],
          pt_id: [{
            required: true,
            message: '请选择规则分类',
            trigger: 'blur'
          }, ],
          range_type: [{
            required: true,
            message: '请选择规则积分类型',
            trigger: 'blur'
          }, ],
        },
        point_types: [],
        range_type_arr: [{
            name: '固定分值',
            value: '1'
          },
          {
            name: '范围分值',
            value: '2'
          },
        ],
        integral_select: [{
            name: '奖分',
            value: '1'
          },
          {
            name: '扣分',
            value: '2'
          },
        ],
        integral_select_name1: '1',
        integral_select_name2: '1',



        defaultProps: {
          children: 'child',
          label: 'name'
        },
        options: [],
        types_list: {},
        show_employee_selector: false,
        select_mode: false,
        show_dept_selector: false,
        edit_dept_show: false,
        add_dept_show: false,
        dept_formdata: {
          name: '',
          pid: '0',
          cycle_type: '1'
        },
        company_info: {},
        actions_show: false,
        edit_dept_name: '',
        dept_name: '积分规则',
        dialog_title: '添加分类',
        dept_id: 0,
        dept_pid: 0,
        list: [],
        dept_list: [],
        keyword: '',
        owner_id: 0,
        user_info: this.$store.getters.user_info,
        employee_selected_list: [],
        dept_selected_list: [],
        employee_selected: [],
        dept_selected: [],
        selected_box_width: '0',
        rule_category_list: [],
        pid: 0,
        pid_list: [],
        pid_list_arr: [],
        item_list: [],
        cur_item_list: [],
        dept_loading: false,
        tips_show: false,

        import_rules_show: false,
        save_loading: false,
        import_btn_show: false,
        fileList: [],
        file: null,

        ruleTreeList: [],//规则分类列表
        ruleTree_pid: [],//上级分类Pid
        itemRule_id: [],//所属分类rule_id
      }
    },
    watch: {
      pid(val) {
        if (val == 0) {
          this.dept_id = 0
          this.dialog_title = '添加分类'
          this.list = []
          for (let i in this.item_list) {
            for (let k in this.item_list[i]) {
              this.list.push(this.item_list[i][k])
            }
          }
        } else {
          this.rule_category_list = []
          this.parse_tree(this.dept_list, val)
          this.list = this.cur_item_list
          this.dialog_title = '添加子分类'
        }
      },
      employee_selected_list() {
        let l = this.employee_selected_list.length + this.dept_selected_list.length
        let width = 0.9 * l;
        this.selected_box_width = width + 'rem'
      },
      dept_selected_list() {
        let l = this.employee_selected_list.length + this.dept_selected_list.length
        let width = 0.9 * l;
        this.selected_box_width = width + 'rem'
      },
      keyword() {

      }
    },
    methods: {
      //导出规则按钮
      derivedRule(){
        let token = getToken()?getToken():this.$getToken
        window.open(this.publicBASE_API+'/api/download/rule_item/item?employee_id='+this.$store.getters.user_info.id +'&token='+token)
      },
      //规则为空时点击 导入规则按钮
      theImportRules(){
        if(this.dept_list.length == 0){
          if(PerformTheNumber){
            this.$message({
              message: '请先完善规则分类',
              duration:2000,
              type: 'warning'
            });
            PerformTheNumber = false;
            setTimeout(()=>{
              PerformTheNumber = true
            },5000)
          }else{
            console.log('不执行')
          }
        }else{
          this.import_rules_show = true
        }
      },
      //点击搜索
      onFilterChanged: function() {
        this.get_department_list()
      },
      close_import(){
        this.import_rules_show = false
        this.$refs.upload.clearFiles()
      },

    //关闭错误信息时的回调
      error_list_SX(){
        this.get_department_list()
      },
      submitUpload() {
        this.save_loading = true
        let params = {
          file: this.file
        }
        this.$http('post','/api/rule/import', params).then(res => {
          if(res.data.code == 1) {
            this.import_rules_show = false;
            this.$message.success({message:res.data.msg})
            // if(res.data.data.list.length != 0){
            //   this.error_list_show = true
            //   this.error_list.push(res.data.data)
            // }else{
            //   this.$message.success({message:res.data.msg})
            // }
            if(res.data.data.length != 0 && res.data.data.length != undefined){
              this.error_list_show = true
              this.error_list = res.data.data
            }else{
              this.get_department_list()
            }
          }else{
            this.$message({type:'error',message:res.data.msg})
          }
        }).finally(()=>{
          this.save_loading = false
        })
      },
      handleSuccess(response) {
        if(response.code == 1) {
          this.file = response.data;
        }
      },
      handleRemove(file, fileList) {
        if (fileList !== null && fileList.length != 0) {
          this.import_btn_show = true
        }else{
          this.import_btn_show = false
        }
      },
      handlePreview(file) {
        console.log(file);
      },
      imgChange(file, fileList){
        if (fileList !== null && fileList.length != 0) {
          this.import_btn_show = true
        }else{
          this.import_btn_show = false
        }
      },
      beforeFilesUpload(file) {
        const $ext_list = ['xlsx', 'xls'];
          let len =  file.name.split('.').length - 1;
          const $ext_name = file.name.split('.')[len]
          if ($ext_list.indexOf($ext_name) != -1) {
            this.import_btn_show = true
          }else {
            this.$message.warning('文件格式上传错误,仅支持上传xlsx,xls）')
            return false
          }
      },
      get_item_list(trees){
        if(this.item_list['rule_'+trees.id]){
          for(let i in this.item_list['rule_'+trees.id]){
            this.cur_item_list.push(this.item_list['rule_'+trees.id][i])
          }
        }
        for (let i in trees.child) {
          this.get_item_list(trees.child[i])
        }
      },
      edit_cate() {
        let query = {
          rule_id: this.pid_list_arr[this.pid_list_arr.length - 1].id,
          rule_name: this.pid_list_arr[this.pid_list_arr.length - 1].name
        }
        if (this.pid_list_arr.length > 1) {
          query['pid'] = this.pid_list_arr[this.pid_list_arr.length - 2].id
          query['pname'] = this.pid_list_arr[this.pid_list_arr.length - 2].name
        } else {
          query['pid'] = 0
          query['pname'] = ''
        }
        this.$router.push({
          name: 'rule_category_edit',
          query: query
        })
      },
      back() {
        this.back_by_index(this.pid_list_arr.length - 1)
      },
      parse_tree(trees, rule_id) {
        for (let i in trees) {
          if (rule_id == trees[i].id) {
            this.cur_item_list = []
            this.get_item_list(trees[i])
          }
          this.rule_category_list.push(trees[i])
          this.parse_tree(trees[i].child, rule_id)
        }
      },
      set_manager(dat) {
        //设置上级，这里请求接口
      },
      move_to() {
        this.show_dept_selector = true
      },
      plus_menu(val) {
        switch (val) {
          case 'add_cate_btn':
            this.$router.push({
              name: 'rule_category_add',
              query: {
                rule_id: this.dept_id,
                rule_name: this.dept_name
              }
            })
            break;
          case 'add_rule':
            this.$router.push({
              name: 'rule_item_add',
              query: {
                rule_name: this.dept_name,
                rule_id: this.dept_id
              }
            });
            break;
        }
      },
      move_cancel() {
        this.select_mode = false
        this.employee_selected_list = []
        this.dept_selected_list = []
        this.employee_selected = []
        this.dept_selected = []
      },
      move_confirm(data) {

        //移动成员，这里请求接口

        let self = this
        this.$http('post','/addons/ems/employee/move_employee_and_dept', {
          pid: data.dept.length > 0 ? data.dept[0].id : 0,
          employee_ids: this.employee_selected.toString(),
          dept_ids: this.dept_selected.toString()
        }).then((res) => {
          if (res.data.code == 1) {
            self.get_user_list(function() {

            })
            self.$toast(res.data.msg)
          } else {
            self.$toast(res.data.msg)
          }
        }).catch((error) => {

        })
        this.select_mode = false
        this.employee_selected_list = []
        this.dept_selected_list = []
        this.employee_selected = []
        this.dept_selected = []
      },
      cancel_select() {
        this.select_mode = false
      },
      employee_cancel(item) {
        this.employee_selected.splice(this.employee_selected.indexOf(item.id), 1)
        let delete_index = -1
        for (let i in this.employee_selected_list) {
          if (this.employee_selected.indexOf(this.employee_selected_list[i].id) < 0) {
            delete_index = i
          }
        }
        if (delete_index >= 0) {
          this.employee_selected_list.splice(delete_index, 1)
          for (let i in this.list) {
            if (this.list[i].id == item.id) {
              this.$set(this.list[i], 'checked', false)
            }
          }
        }
      },
      dept_cancel(item) {
        this.dept_selected.splice(this.dept_selected.indexOf(item.id), 1)
        let delete_index = -1
        for (let i in this.dept_selected_list) {
          if (this.dept_selected.indexOf(this.dept_selected_list[i].id) < 0) {
            delete_index = i
          }
        }
        if (delete_index >= 0) {
          this.dept_selected_list.splice(delete_index, 1)
          for (let i in this.dept_list) {
            if (this.dept_list[i].id == item.id) {
              this.$set(this.dept_list[i], 'checked', false)
            }
          }
        }
      },
      select_employee(item) {
        if (item.checked) {
          item.checked = false
          this.employee_cancel(item)
        } else {
          this.employee_selected.push(item.id)
          this.employee_selected_list.push({
            id: item.id,
            name: item.name,
            avatar: item.avatar
          })
          item.checked = true
        }
      },
      select_dept(item) {
        if (item.checked) {
          item.checked = false
          this.dept_cancel(item)
        } else {
          this.dept_selected.push(item.id)
          this.dept_selected_list.push({
            id: item.id,
            name: item.name,
            avatar: 'static/images/e66f.jpg'
          })
          item.checked = true
        }
      },
      employee_click(item) {
        if (this.select_mode) {
          //选择
          this.select_employee(item)
        } else {
          localStorage.setItem('rule_' + item.id, JSON.stringify(item))
          let dept_name = ''
          let rule_id = ''
          for (let i in this.rule_category_list) {
            if (item.rule_id == this.rule_category_list[i].id) {
              dept_name = this.rule_category_list[i].name
              rule_id = this.rule_category_list[i].id
            }
          }
          this.$router.push({
            name: 'rule_item_edit',
            query: {
              id: item.id,
              rule_name: dept_name,
              rule_id: rule_id
            }
          });
        }
      },
      show_child(item) {
        // this.dept_formdata.pid = item.pid
        this.pid_list.push(this.pid)
        this.pid_list_arr.push(item)
        this.pid = item.id
        this.class_item = item
        let item1 = JSON.parse(JSON.stringify(item))
        this.dept_name = item1.name
        this.show_edit_btn = true
        this.dept_id = item1.id
        this.dept_pid = item1.pid
      },
      dept_click(item) {
        if (this.select_mode) {
          //选择
          this.select_dept(item)
        } else {
          this.show_child(item)
        }
      },
      add_employee() {
        this.$router.push({
          name: 'rule_item_add',
          query: {
            rule_id: this.dept_id
          }
        });
      },
      submit_edit_dept() {
        let self = this
        this.$http('put','/api/integral/rule', {
          name: this.edit_dept_name,
          rule_id: this.dept_id,
          pid: this.dept_pid
        }).then((res) => {
          if (res.data.code == 1) {
            self.$toast(res.data.msg)
          } else {
            self.$toast(res.data.msg)
          }
        }).catch((error) => {

        })
      },
      show_add_dept() {
        this.add_dept_show = true
        this.dept_formdata.name = ''
        this.$nextTick(() => {
          setTimeout(() => {
            document.getElementById('dept_add_input').classList.add('focus_hidden_input')
            document.getElementById('dept_add_input').focus()
            document.getElementById('dept_add_input').classList.remove('focus_hidden_input')
          }, 200)
        })
      },
      actions_select(item, index) {
        if (item.action == 'edit') {
          this.dept_formdata.id = this.pid
          this.edit_dept_show = true
          this.edit_dept_name = JSON.parse(JSON.stringify(this.dept_name))
          this.$nextTick(() => {
            setTimeout(() => {
              document.getElementById('dept_edit_input').classList.add('focus_hidden_input')
              document.getElementById('dept_edit_input').focus()
              document.getElementById('dept_edit_input').classList.remove('focus_hidden_input')
            }, 200)
          })
          //修改部门名称
        }
        if (item.action == 'delete') {
          this.$dialog.confirm({
            title: '删除分类',
            message: '确定要删除当前分类吗？'
          }).then(() => {
            this.del_dept()
          }).catch(() => {
            // on cancel
          });
        }

        if (item.action == 'move_employee') {
          this.select_mode = true
        }
        if (item.action == 'set_manager') {
          this.show_employee_selector = true
        }
        this.actions_show = false
      },
      del_dept() {
        this.$confirm('此操作将永久删除该分组, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http('delete','/api/integral/rule',{rule_id: this.dept_id}).then((res) => {
            if (res.data.code == 1) {
              this.$message.success(res.data.msg)
              this.get_department_list(function() {})
              this.dept_name = '积分分类'
              this.show_edit_btn = false
              this.class_show = false
            } else {
              this.$message.error(res.data.msg)
            }
          })
        })
      },
      submit_add_dept(form) {
        let self = this
        self.$refs[form].validate((valid) => {
          if (valid) {
            if (self.class_type == 'edit') {
              delete self.dept_formdata.child
              // self.dept_formdata.pid = self.class_item.pid || 0
              // self.dept_formdata.pid = self.class_item.pid[self.class_item.pid.length - 1] || 0
              if(self.dept_formdata.pid.length>0){
                self.dept_formdata.pid = self.dept_formdata.pid[self.dept_formdata.pid.length - 1] || 0
              }else{
                self.dept_formdata.pid = 0;
              }
              self.dept_formdata.rule_id = self.dept_formdata.id
              this.$http('put','/api/integral/rule', self.dept_formdata).then((res) => {
                if (res.data.code == 1) {
                  self.$message.success('修改积分规则成功')
                  self.get_department_list(function() {})
                } else {
                  self.$message.error(res.data.msg)
                }
              }).catch((error) => {})
            } else {
              if (self.dept_formdata.pid !== null && self.dept_formdata.pid.length == 0) {
                self.dept_formdata.pid = 0
              } else {
                self.dept_formdata.pid = self.dept_formdata.pid[self.dept_formdata.pid.length - 1]
              }
              this.$http('post','/api/integral/rule', self.dept_formdata).then((res) => {
                if (res.data.code == 1) {
                  self.get_department_list(function() {})
                } else {
                  self.$message.error(res.data.msg)
                }
              }).catch((error) => {})
            }
            self.class_show = false
          } else {
            return false;
          }
        });
      },
      add_dept_close(form) {
        this.class_show = false
        this.$refs[form].resetFields()
      },
      ruleTree_list(rule){
        rule.forEach((item)=>{
          this.ruleTreeList.push({
            id: item.id,
            pid: item.pid
          })
          if(item.child.length > 0){
            this.ruleTree_list(item.child)
          }
        })
      },
      get_department_list(done) {
        this.dept_loading = true
        this.$http('get','/api/integral/rule/trees',{cycle_type: '1',keyword:this.keyword}).then((res) => {
          this.dept_list = res.data.data.rule_tree
          //展开多维数组分类rule_tree。
          this.ruleTreeList = []
          this.ruleTree_list(res.data.data.rule_tree)

          this.rule_category_list = []
          this.item_list = res.data.data.item_list


          this.parse_tree(this.dept_list, this.pid)
          if (this.pid > 0) {
            this.list = this.cur_item_list
          } else {
            this.list = []
            for (let i in this.item_list) {
              for (let k in this.item_list[i]) {
                this.list.push(this.item_list[i][k])
              }
            }
          }
          this.dept_loading = false
          done()
        }).catch((e) => {
          done()
        })
      },
      back_by_index(index) {

        if (index == this.pid_list.length) {
          return false
        }
        this.pid = this.pid_list[index]
        this.pid_list.splice(index, 100)
        this.pid_list_arr.splice(index, 100)
        this.get_department_list(function() {

        })
      },
      get_join_review_list() {},
      get_user_list(done) {
        this.$toast.loading({
          message: '加载中...',
          forbidClick: true
        });
        this.$http('get','/addons/ems/employee/get_dept_list',{pid: this.dept_formdata.pid,keyword: this.keyword}).then((res) => {
          for (let i in res.data.data.employee_list) {
            res.data.data.employee_list[i]['checked'] = false
          }
          for (let i in res.data.data.dept_list) {
            res.data.data.dept_list[i]['checked'] = false
          }
          this.list = res.data.data.employee_list
          this.dept_list = res.data.data.dept_list
          this.owner_id = res.data.data.owner_id
          this.company_info = res.data.data.company_info

          done()
          this.$toast.clear()
        }).catch((e) => {
          done()
          this.$toast.clear()
        })
      },
      get_point_types() {
        let self = this
		let list=JSON.parse(localStorage.getItem('SET_POINT_TYPES'));
        for (let i in list) {
          self.types_list[list[i].id] = list[i].name
        }
        self.point_types = list
      },

      add_class() {
        this.class_show = true
        this.class_type = 'add'
        this.dept_formdata = {
          name: '',
          pid: '0',
          cycle_type: '1'
        }
      },
      //递归寻找当前点击的所有上级id。
      ruleTree_data(id,ifs){
        let that = ifs ? this.ruleTree_pid : this.itemRule_id
        let list = this.ruleTreeList
        that.unshift(id)
        list.some((item)=>{
          if(item.id == id){
            if(item.pid > 0){
              this.ruleTree_data(item.pid,ifs)
            }else{
              if(ifs){
                this.dept_formdata.pid = that
              }else{
                this.rules_detail_form.rule_id = that
              }
              return true
            }
          }
        })
      },
      edit_class() {
        this.dept_formdata = JSON.parse(JSON.stringify(this.class_item))
        //整合上级分类格式变为可选中状态 Pid。让上级分类变为选中
        this.ruleTree_pid = []
        if(this.dept_formdata.pid > 0){
          this.ruleTree_data(this.dept_formdata.pid,true)
        }

        this.class_show = true
        this.class_type = 'edit'
      },
      handleSelectionChange(val) {
        this.del_item_id = []
        val.forEach(element => {
          this.del_item_id.push(element.id)
        });
      },
      del_item() {
        if (this.del_item_id.length == 0) {
          this.$message.error('请选择积分细则')
          return false
        }
        this.$confirm('此操作将永久删除该选项, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let data = {
            item_id: this.del_item_id
          }
          this.$http('delete','/api/integral/rule/items',data).then((res) => {
            if (res.data.code == 1) {
              this.$message.success(res.data.msg)
              this.get_department_list(function() {})
            } else {
              this.$message.error(res.data.msg)
            }
          }).catch((e) => {
            this.$message.error(e.data.msg)
          })
        })
      },
      add_rule() {
        this.rule_show = true
        this.rule_type = 'add'
        this.rules_detail_form = {
          rule_id: '',
          range_type: '1',
          prize_type: '0',
          min_point: '',
          max_point: '',
          remark: '',
          is_attendance: '0',
          cycle_type: '1',
          pt_id: 2
        }
        this.integral_select_name1 = '1'
        this.integral_select_name2 = '1'
      },
      not_data() {
        this.$confirm('暂时没有积分分类,是否前往添加?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.rule_show = false
          this.class_show = true
        }).catch(() => {});
      },
      cascader_close(val){
        // let rule_ids = '';
        // for(let i in val){
        //   rule_ids = val[i]
        // }
        // this.rules_detail_form.rule_id = rule_ids
        this.$refs.cascaderHandle.dropDownVisible = false; //监听值发生变化就关闭它
      },
      cascader_closeSJ(val){
        this.$refs.cascaderHandleSJ.dropDownVisible = false; //监听值发生变化就关闭它
      },
      select_rule(val) {
        if (!val) {
          this.rules_detail_form.rule_id = this.rules_detail_form.rule_id[this.rules_detail_form.rule_id.length - 1]
        }
      },
      del_rule() {
        let self = this
        let data = {
          item_id: [this.rules_detail_form.id]
        }
        self.$confirm('此操作将永久删除该选项, 是否继续?', '提示').then(() => {
          self.$http('delete','/api/integral/rule/items',data,).then((res) => {
            if (res.data.code == 1) {
              self.$message.success(res.data.msg)
              self.get_department_list(function() {})
              self.rule_show = false
            } else {
              self.$message.error(res.data.msg)
            }
          }).catch((e) => {
            self.$message.error(e.data.msg)
          }).finally(() => {
            self.loading = false
          })
        }).catch(() => {});
      },
      rule_close(form) {
        this.rule_show = false
        this.$refs[form].resetFields()
      },
      add_submit_rule(form) {
        let self = this
        self.$refs[form].validate((valid) => {
          if (valid) {
            if (self.integral_select_name1 != '1' && self.rules_detail_form.min_point >= 0) {
              self.rules_detail_form.min_point = '-' + self.rules_detail_form.min_point
            }
            if (self.integral_select_name2 != '1' && self.rules_detail_form.max_point >= 0) {
              self.rules_detail_form.max_point = '-' + self.rules_detail_form.max_point
            }
            if (self.rules_detail_form.range_type == 1) {
              self.rules_detail_form.max_point = self.rules_detail_form.min_point
            }
            if (parseFloat(self.rules_detail_form.min_point) > parseFloat(self.rules_detail_form.max_point)) {
              this.$confirm('填写的规则积分是' + self.rules_detail_form.min_point + ' ～ ' + self.rules_detail_form.max_point +
                '，应该是 ' + self.rules_detail_form.max_point + ' ～ ' + self.rules_detail_form.min_point + '吧？',
                '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                let min_point = self.rules_detail_form.min_point
                self.rules_detail_form.min_point = self.rules_detail_form.max_point
                self.rules_detail_form.max_point = min_point
                if(self.rules_detail_form.min_point == 0 && self.rules_detail_form.range_type == 1){
                  self.$message.error('积分不能为零')
                  return false
                }
                let data = {
                  items: [self.rules_detail_form]
                }
                if(typeof data.items[0].rule_id == 'object') data.items[0].rule_id = data.items[0].rule_id[data.items[0].rule_id.length - 1]
                this.$http('post','/api/integral/rule/items', data).then((res) => {
                  if (res.data.code == 1) {
                    self.$message.success(res.data.msg)
                    self.$refs[form].resetFields()
                    self.rule_show = false
                    self.get_department_list(function() {});
                  } else {
                    self.$message.error(res.data.msg)
                  }
                }).catch((e) => {
                  self.$message.error(e.data.msg)
                });
              }).catch(() => {});
            } else {
              self.rules_detail_form.item_id=self.rules_detail_form.id
              if(self.rules_detail_form.min_point == 0 && self.rules_detail_form.range_type == 1){
                self.$message.error('积分不能为零')
                return false
              }
              let data = {
                items: [self.rules_detail_form]
              }
              if(typeof data.items[0].rule_id == 'object') data.items[0].rule_id = data.items[0].rule_id[data.items[0].rule_id.length - 1]
              this.$http('post','/api/integral/rule/items', data).then((res) => {
                if (res.data.code == 1) {
                  self.$message.success(res.data.msg)
                  self.$refs[form].resetFields()
                  self.rule_show = false
                  self.get_department_list(function() {});
                } else {
                  self.$message.error(res.data.msg)
                }
              }).catch((e) => {
                self.$message.error(e.data.msg)
              });
            }
          } else {
            return false;
          }
        })
      },
      edit_submit_rule(form) {
        let self = this
        self.$refs[form].validate((valid) => {
          if (valid) {
            if (self.integral_select_name1 != '1' && self.rules_detail_form.min_point >= 0) {
              self.rules_detail_form.min_point = '-' + self.rules_detail_form.min_point
            }
            if (self.integral_select_name2 != '1' && self.rules_detail_form.max_point >= 0) {
              self.rules_detail_form.max_point = '-' + self.rules_detail_form.max_point
            }
            if (self.rules_detail_form.range_type == 1) {
              self.rules_detail_form.max_point = self.rules_detail_form.min_point
            }
            if (parseFloat(self.rules_detail_form.min_point) > parseFloat(self.rules_detail_form.max_point)) {
              this.$confirm('填写的规则积分是' + self.rules_detail_form.min_point + ' ～ ' + self.rules_detail_form.max_point +
                '，应该是 ' + self.rules_detail_form.max_point + ' ～ ' + self.rules_detail_form.min_point + '吧？',
                '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                let min_point = self.rules_detail_form.min_point
                self.rules_detail_form.min_point = self.rules_detail_form.max_point
                self.rules_detail_form.max_point = min_point
                // let data = self.rules_detail_form
                let datas = self.rules_detail_form
                let data = {}
                for(let key in datas){
                  data[key] = datas[key]
                }
                data.item_id = self.rules_detail_form.id
                if(self.rules_detail_form.min_point == 0 && self.rules_detail_form.range_type == 1){
                  self.$message.error('积分不能为零')
                  return false
                }
                if(typeof datas.rule_id == 'object') data.rule_id = datas.rule_id[datas.rule_id.length - 1]
                this.$http('put','/api/integral/rule/items', data).then((res) => {
                  if (res.data.code == 1) {
                    self.$message.success(res.data.msg)
                    self.$refs[form].resetFields()
                    self.rule_show = false
                    self.get_department_list(function() {});
                  } else {
                    self.$message.error(res.data.msg)
                  }
                }).catch((e) => {
                  self.$message.error(e.data.msg)
                });
              }).catch(() => {});
            } else {
              self.rules_detail_form.item_id=self.rules_detail_form.id
              // let data = self.rules_detail_form
              
              let datas = self.rules_detail_form
              let data = {}
              for(let key in datas){
                data[key] = datas[key]
              }
              data.item_id = self.rules_detail_form.id
              if(self.rules_detail_form.min_point == 0 && self.rules_detail_form.range_type == 1){
                self.$message.error('积分不能为零')
                return false
              }
              if(typeof datas.rule_id == 'object') data.rule_id = datas.rule_id[datas.rule_id.length - 1]
              this.$http('put','/api/integral/rule/items', data).then((res) => {
                if (res.data.code == 1) {
                  self.$message.success(res.data.msg)
                  self.$refs[form].resetFields()
                  self.rule_show = false
                  self.get_department_list(function() {});
                } else {
                  self.$message.error(res.data.msg)
                }
              }).catch((e) => {
                self.$message.error(e.data.msg)
              });
            }
          } else {
            return false;
          }
        })
      },


      editDetails(val) {
        this.rules_detail_form = JSON.parse(JSON.stringify(val))
        //整合上级分类格式变为可选中状态 rule_id。让所属分类变为选中
        this.itemRule_id = []
        if(this.rules_detail_form.rule_id > 0){
          this.ruleTree_data(this.rules_detail_form.rule_id)
        }


        this.rule_show = true
        this.rule_type = 'edit'
        if(this.rules_detail_form.min_point == this.rules_detail_form.max_point){
          this.rules_detail_form.range_type = '1'
        }else{
          this.rules_detail_form.range_type = '2'
        }
        if(this.rules_detail_form.min_point < 0){
          this.integral_select_name1 = '2'
        }else{
          this.integral_select_name1 = '1'
        }

        if(this.rules_detail_form.max_point < 0){
          this.integral_select_name2 = '2'
        }else{
          this.integral_select_name2 = '1'
        }
      },
      tips_close() {
        localStorage.setItem('rule_tips', 'true')
        this.tips_show = false
      },
      // 递归判断列表，把最后的children设为undefined
      getTreeData(data) {
        for (var i = 0; i < data.length; i++) {
          if (data[i].children.length < 1) {
            // children若为空数组，则将children设为undefined
            data[i].children = undefined;
          } else {
            // children若不为空数组，则继续 递归调用 本方法
            this.getTreeData(data[i].children);
          }
        }
        return data;
      },

    },
    mounted() {
      if (localStorage.getItem('rule_tips')) {
        this.tips_show = false
      } else {
        this.tips_show = true
      }
    },
    created() {
      if (this.$route.query.pid) {
        this.dept_formdata.pid = this.$route.query.pid
      }
      this.get_point_types()
      this.get_department_list(function() {

      })

      this.options = [{
          text: '添加分类',
          value: 'add_cate_btn',
          icon: 'cluster-o'
        },
        {
          text: '添加规则',
          value: 'add_rule',
          icon: 'friends-o'
        },
      ]
    },
  }
</script>

<style scoped lang="scss">
  .border-right:after{
    content: " ";
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    width: 1px;
    background: #EBEEF5;
  }
  .border-right{
    position: relative;
  }
  .display-flex {
    display: flex;
    width: 100%;
    background-color: #fff;
    min-height: calc(100vh - 160px);
  }

  .box-right:after {
    content: " ";
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    width: 1px;
    background: #EBEEF5;
  }

  .padding24 {
    padding: 24px;
  }

  .btn-block {
    display: block;
    width: 100%;
  }

  .cate-tree {
    margin-top: 16px;
  }

  .display-flex /deep/ .el-tree-node__content {
    height: 32px;
  }

  .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }

  .el-select .el-input {
    width: 130px;
  }

  .select_width .el-select {
    width: 80px;
  }

  /deep/.el-tree-node__expand-icon.is-leaf {
    color: inherit !important;
  }
  .text-center{
    text-align: center;
  }
  .cate-tree /deep/ .is-focusable .el-tree-node__content:hover{
    background:#F5F7FA !important;
  }
  .diy-tip{
    margin-bottom:15px;background:#f0f9eb!important;color:#67c23a!important;border:1px solid #67c23a;padding:20px 16px;
    p{
      color:#67c23a!important;font-size:14px;margin:0 !important;padding:4px 0;
    }
  }
  .color_green{
    color: #67C23A;
  }
  .color_red{
    color: #F56C6C;
  }
  .color_blue{
    color:#409eff;
  }
  // wei_left_nav
  .rule_class_box{
    /deep/ .el-tree-node{
      border-bottom:1px #f8f8f8 solid;
    }
    /deep/ .el-tree-node__content{
      height:56px;
      line-height:56px;
    }
    /deep/ .is-current .el-tree-node__content .el-icon-caret-right{
      color:#409EFF !important;
    }
    /deep/ .is-current .el-tree-node__content .el-tree-node__label{
      color:#409EFF !important;
    }
    /deep/ .is-current .el-tree-node__children .el-icon-caret-right{
      color:#C0C4CC !important;
    }
    /deep/ .is-current .el-tree-node__children .el-tree-node__label{
      color:#606266 !important;
    }
  }
</style>
