<template>
  <div style=" background-color: #fff; padding:15px;">
    <el-alert title="温馨提示：" type="success" description>
      <p class="diy-tip">1、您可以查看和导出所有员工的A分记录，然后将A分清零；</p>
      <p class="diy-tip">2、A分清零是批量操作，将所有员工的A分全部扣除；</p>
      <p class="diy-tip">3、这里只显示员工的A分总数，需要查看积分详细请点击【<el-button type="text" href="javascript:void(0);" @click="$router.push({path:'event_manage'})">积分事件</el-button> 】；</p>
    </el-alert>
    <div style="margin-top:15px; margin-bottom:15px;" class="inline-block-btn-list">


      <el-cascader
        v-if="false"
        clearable
        :options="deptTree"
        change-on-select
        v-model="filter.dept_id"
        @change="onFilterChanged"
        placeholder="选择部门进行筛选"
        class="gap-right-8"
      ></el-cascader>

      <div style="position:relative; display:inline-block;">
        <el-button @click.stop="show3 = !show3" style="color:rgb(192 196 204); padding-right:25px;">
          <span
            style="max-width: 150px; display: inline-block; overflow: hidden;"
            :class="{'treeActice':textTip != '选择部门进行筛选'}"
          >{{textTip}}</span>
          <span class="el-input__suffix">
            <span class="el-input__suffix-inner">
              <i :class="{'arrRotation': show3}" class="el-input__icon el-icon-arrow-down"></i>
            </span>
          </span>
        </el-button>
        <el-collapse-transition>
          <div
            v-show="show3"
            style="margin-top:10px;
             padding:6px 0;
             max-height:250px;
             min-width: 180px;
             overflow: auto;
             position:absolute;
             z-index:99;
             border: 1px solid #e4e7ed;
             border-radius: 2px;
             background:#fff;
             box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);"
          >
            <el-tree
              node-key="value"
              ref="tree"
              :data="deptTree"
              :accordion="true"
              :highlight-current="true"
              :props="defaultProps"
              show-checkbox
              @check="handleCheck"
            ></el-tree>
          </div>
        </el-collapse-transition>
      </div>

      <div class="gap-right-8" style="display:inline-block; width:220px;">
        <el-input
          placeholder="输入关键词查找"
          ref="search-bar"
          v-model="filter.keywords"
          class="input-with-select"
          @keyup.enter.native="onFilterChanged"
        >
          <el-button slot="append" icon="el-icon-search" @click="onFilterChanged"></el-button>
        </el-input>
      </div>



      <el-button
        @click="downloadSheet"
        v-show="accessEnabled.excel_import == 1"
        type="primary"
        plain
      >导出A分记录</el-button>

      <el-button
        @click="deduct_a_point_show1 = true"
        v-show="accessEnabled.excel_import == 1"
        type="primary"
        plain
      >A分清零</el-button>
    </div>
    <el-table
      @filter-change="filterHandler"
      v-loading="loading"
      ref="multipleTable"
      :data="tableData"
      :border="false"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >

      <el-table-column prop="company_id" label="工号"></el-table-column>
      <el-table-column prop="name" label="姓名"></el-table-column>
      <el-table-column
        prop="dept_name"
        column-key="dept"
        :filterMultiple="false"
        :filters="department_list"
        label="部门"
      ></el-table-column>
      <el-table-column prop="superior_name" label="A分">

        <template slot-scope="scope">
          <div>{{ scope.row.reward_points_a - scope.row.deduct_points_a }}</div>
        </template>

      </el-table-column>

    </el-table>
    <el-pagination
      background
      layout="total,sizes, prev, pager, next"
      @size-change="handleSizeChange"
      :page-size="pageLimit"
      :page-sizes="[10, 20, 50, 100]"
      :total="totalCount"
      :current-page.sync="currentPage"
      @current-change="changePage"
    ></el-pagination>
    <el-dialog
      title="Excel管理"
      width="600px"
      :visible.sync="dialogExcelVisible"
      :close-on-click-modal="false"
    >
      <div style="padding:0 50px;">
        <div class="align-center" style="margin-bottom:20px;">
          <p>温馨提示：</p>
          <p>1、导入之前请点击“下载模板”按钮下载模板文件；</p>
          <p>2、填写员工信息到Excel电子表中；</p>
          <p>3、点击“Excel文件导入”上传填写好的电子表；</p>
          <p>4、支持上传大小500KB以内的Excel文件。</p>
          <p></p>
        </div>
        <div class="align-center" style="margin-bottom:20px; float:left;">
          <a
            target="_blank"
            :href="serverdomain+'/integral.php/excel_util/download_employee_template'"
          >
            <el-button type="primary" plain>下载模板</el-button>
          </a>
        </div>
        <div class="align-center" style="margin-bottom:20px; float:left; margin-left:10px;">
          <el-upload
            :action="serverdomain+'/integral.php/excel_util/test_link'"
            :show-file-list="false"
            :http-request="uploadFile"
            v-show="accessEnabled.excel_import == 1"
          >
            <el-button type="primary">Excel导入</el-button>
          </el-upload>
        </div>
        <div class="align-center" style="margin-bottom:20px; float:left; margin-left:10px;">
          <el-button type="primary" @click="downloadSheet">Excel导出</el-button>
        </div>
        <div style="clear:both;"></div>
      </div>
    </el-dialog>

    <el-dialog
      ref="EditInformation_list"
      title="添加员工"
      width="860px"
      @close="detailFormreturn"
      :visible.sync="dialogTableVisible"
      :close-on-click-modal="false"
    >
      <EmployeeTableshow ref="EditInformation"></EmployeeTableshow>
    </el-dialog>


    <el-dialog
      :title="deduct_a_point_title"
      width="400px"
      :visible.sync="deduct_a_point_show"
      :close-on-click-modal="false"
    >




      <el-form @submit.native.prevent style="padding-right:20px;" ref="deduct_A_form" :model="deduct_a_point" :rules="deduct_points_arules">
        <el-form-item label="历史扣除" label-width="100px">
        {{deduct_points_a}}
      </el-form-item>
        <el-form-item label="剩余积分" label-width="100px">
          {{reward_points_a}}
        </el-form-item>
        <el-form-item label="扣除积分" prop="name" label-width="100px">
          <el-input-number v-model="deduct_a_point.point" :min="0" :max="reward_points_a" label="扣除积分"></el-input-number>
        </el-form-item>


        <el-form-item label="备注" prop="remark" label-width="100px">
          <el-input type="textarea" v-model="deduct_a_point.remark"></el-input>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">

        <el-button type="primary" :loading="deduct_point_loading" @click="deduct_A_confirm">提 交</el-button>
      </div>



    </el-dialog>

    <el-dialog
      :title="deduct_a_point_title1"
      width="400px"
      :visible.sync="deduct_a_point_show1"
      :close-on-click-modal="false"
    >


      <el-alert
        title="A分清零后不能恢复，建议先导出Excel" style="margin-bottom:15px;"
        type="warning">
      </el-alert>

      <el-form @submit.native.prevent ref="deduct_A_form1" :model="deduct_a_point1" :rules="deduct_points_arules1">


        <el-form-item prop="remark">

          <el-input type="textarea" v-model="deduct_a_point1.remark" placeholder="请填写备注，方便以后核查"></el-input>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">

        <el-button type="primary" :loading="deduct_point_loading1" @click="deduct_A_confirmAll">提 交</el-button>
      </div>



    </el-dialog>

  </div>
</template>
<script>
import EmployeeTableshow from '@/views/integral/EmployeeTableshow'
import EmployeeAPoint from '@/views/integral/EmployeeAPoint'
import qs from 'qs'
export default {
  components: {
    EmployeeTableshow, EmployeeAPoint
  },

  data() {
    return {
      deduct_point_loading: false,
      deduct_points_arules: {
        remark: [
          { required: true, message: '请输入备注', trigger: 'blur' }
        ]
      },
      deduct_a_point: {
        point: 0,
        employee_id: 0,
        remark: ''
      },
      deduct_points_a: 0,
      reward_points_a: 0,
      deduct_a_point_title: '',
      deduct_a_point_show: false,

      deduct_point_loading1: false,
      deduct_points_arules1: {
        remark: [
          { required: true, message: '请输入备注', trigger: 'blur' }
        ]
      },
      deduct_a_point1: {
        point: 0,
        employee_id: 0,
        remark: ''
      },
      deduct_points_a1: 0,
      reward_points_a1: 0,
      deduct_a_point_title1: 'A分清零',
      deduct_a_point_show1: false,

      show3: false,
      textTip: '选择部门进行筛选',
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      loading: false,
      settings: this.$store.getters.system_setting,
      profile: this.$store.getters.user_info,
      accessEnabled: false,
      dialogTableVisible: false,
      filter: {
        dept_id: [],
        status: 1,
        keywords: ''
      },
      totalCount: 0,
      pageLimit: 10,
      currentPage: 1, // 不缓存页面，因为el-pagination此处有一个bug
      tableData: null,
      multipleSelection: [],
      dialogExcelVisible: false,
      deptTree: [],
      creatorId: '',
      department_list: [],
      employeeStatus: [
        {
          value: 1,
          label: '正常'
        },
        {
          value: 2,
          label: '请假'
        },
        {
          value: 0,
          label: '离职'
        },
        {
          value: -1,
          label: '禁用'
        }
      ],
      accessEnabled: {
        add: 0,
        delete: 0,
        excel_import: 0,
        edit: 0
      }
    }
  },
  methods: {
    deduct_A(row) {
      /* this.$http
        .get('/integral.php/ajax_request_common/exchange_point_a').then(res => {

          if(res.data.status == 0){
            this.$message.error(res.data.info)
          }else{

          }
      })*/
      this.deduct_a_point_title = '操作【' + row.name + '】的A分'
      this.deduct_a_point_show = true
      this.deduct_a_point.employee_id = row.id
      this.deduct_a_point.point = row.reward_points_a
      this.reward_points_a = row.reward_points_a - row.deduct_points_a
      this.deduct_points_a = row.deduct_points_a
    },
    managerType(row, column, cellValue) {
      return row.is_admin == 1 ? '超级管理员' : cellValue
    },
    handleCheck(target, param) {
      this.textTip = ''
      const textTip = []
      this.$refs.tree.getCheckedNodes().forEach(item => {
        textTip.push(item.label)
      })
      this.textTip = textTip.join('、')
      if (param.checkedKeys.length == 0) {
        this.textTip = '选择部门进行筛选'
        // this.show3 = false;
      }
      this.filter.dept_id = param.checkedKeys
      this.onFilterChanged()
      this.show3 = false
    },
    deduct_A_confirm: function() {
      var form = this.$refs['deduct_A_form']
      var self = this
      form.validate((valid) => {
        if (valid) {
          self.deduct_point_loading = true
          this.$http('post','/integral.php/ajax_request_common/exchange_point_a',qs.stringify(self.deduct_a_point)
          ).then(res => {
            self.deduct_point_loading = false
            if (res.data.status == 1) {
              self.$message.success(res.data.info)
              self.deduct_a_point_show = false
              form.clearValidate()
            } else {
              self.$message.error(res.data.info)
            }
          })
        } else {
          // console.log('验证未通过');
          return false
        }
      })
    },
    deduct_A_confirmAll: function() {
      var form = this.$refs['deduct_A_form1']
      var self = this
      form.validate((valid) => {
        if (valid) {
          self.deduct_point_loading1 = true
          this.$http('post','/integral.php/ajax_request_common/exchange_point_a_all',{remark: self.deduct_a_point1.remark}).then(res => {
            self.deduct_point_loading1 = false
            if (res.data.status == 1) {
              self.$message.success(res.data.info)
              self.deduct_a_point_show1 = false
              form.clearValidate()
              self.onFilterChanged()
            } else {
              self.$message.error(res.data.info)
            }
          })
        } else {
          // console.log('验证未通过');
          return false
        }
      })
    },

    send_verify_sms(employee_id) {
      const self = this
      let url = '/integral.php/ajax_request_common/send_verify_code_by_employee_id'
      if (employee_id == 0) {
        url = '/integral.php/ajax_request_common/send_verify_code'
      }
      this.$http('get',url,{employee_id: employee_id})
        .then(function(response) {
          if (response.status == 200) {
            if (response.data.code == 1) {
              self.loadEmployeeList()
              self.$message({
                message: response.data.msg,
                type: 'success'
              })
            } else {
              self.$message({
                message: response.data.msg,
                type: 'error'
              })
            }
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },

    filterHandler(value) {
      console.log(value)

      if (typeof value.dept !== 'undefined' && value.dept.length == 0) {
        this.filter.dept_id = 0
      }
      if (typeof value.dept !== 'undefined' && value.dept.length > 0) {
        this.filter.dept_id = value.dept
      }

      this.onFilterChanged()
    },

    EmployeeAdd() {
      this.dialogTableVisible = true
      const self = this
      this.$nextTick(() => {
        self.$refs['EditInformation'].editMode = false
        self.$refs['EditInformation'].clearForm()
        self.$refs['EditInformation'].formrset()
        console.log(self.$refs['EditInformation'])
      })
    },
    handleSizeChange(val) {
      this.pageLimit = val
      this.onFilterChanged()
    },

    onFilterChanged: function() {
      this.currentPage = 1
      this.loadEmployeeList()
    },
    toggleSelection: function(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange: function(val) {
      this.multipleSelection = val
    },
    isSelectable: function(row, index) {
      return (
        row.id != this.creatorId &&
        row.id != this.profile.id &&
        this.accessEnabled.delete == 1
      )
    },
    toSexName: function(row, column, cellValue) {
      return cellValue == '1' ? '女' : '男'
    },
    dateFormatter: function(row, column, cellValue) {
      return this.$moment(cellValue * 1000).format('YYYY年MM月DD日')
    },
    // 获取基本数据
    loadBaseData: function() {
      var self = this
      this.$http('get','/integral.php/ajax_request_common/get_org_base',{site_id: this.$store.getters.site_id})
        .then(function(response) {
          if (response.status == 200) {
            var jsonData = response.data
            try {
              self.deptTree = jsonData.tree
              self.creatorId = jsonData.creator_id
            } catch (err) {
              console.log(err)
            }
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    // 获取员工列表
    loadEmployeeList: function() {
      var self = this
      self.loading = true
      const params = {
        site_id: this.$store.getters.site_id,
        page: this.currentPage,
        interval: this.pageLimit
      }
      for (const item in this.filter) {
        const value = this.filter[item]
        if (item == 'dept_id') {
          if (!value || value.length == 0) {
            continue
          }
          params[item] = value
          // params[item] = value[value.length - 1]
        } else {
          const valueStr = value.toString()
          if (valueStr && valueStr.length > 0) {
            params[item] = valueStr
          }
        }
      }
      this.$http('get','/integral.php/ajax_request_common/get_employee_list',params)
        .then(function(response) {
          if (response.status == 200) {
            self.loading = false
            var jsonData = response.data
            try {
              self.department_list = jsonData.filter_list.department
              self.totalCount = jsonData.total_count
              self.tableData = jsonData.list_data
            } catch (err) {
              console.log(err)
            }
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    changePage: function(current) {
      if (isNaN(current) || current < 1) {
        return false
      }
      this.loadEmployeeList()
    },
    delEmployee: function(employeeId) {
      this.$confirm('确定要删除此员工吗?', '删除员工', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.deleteItem(employeeId)
        })
        .catch(() => {
          // console.log('已取消删除');
        })
    },
    confirmMultipleDelete: function() {
      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: function(employeeId, isMultiple) {
      if (!employeeId) {
        return false
      }
      isMultiple = isMultiple || false
      let url = ''
      let params = null
      if (isMultiple) {
        url = '/integral.php/ajax_request_common/delete_employee_multiple'
        params = {
          ids: employeeId
        }
      } else {
        url = '/integral.php/ajax_request_common/delete_employee'
        params = {
          id: employeeId
        }
      }
      var self = this
      this.$http('get',url,params)
        .then(function(response) {
          var message = ''
          var 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.loadEmployeeList()
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },

    detailFormreturn: function() {
      this.$refs['EditInformation'].formrset()
    },

    toDetailPage: function(id, event) {
      this.dialogTableVisible = true
      const self = this
      this.$nextTick(() => {
        self.$refs['EditInformation'].clearForm()
        self.$refs['EditInformation'].loadEmployeeDetail(id)
        self.$refs['EditInformation'].editMode = true
      })

      return

      const routerParams = {
        name: 'employee_detail',
        params: {
          targetId: id > 0 ? id : 0
        }
      }
      this.$router.push(routerParams)
    },
    saveStorage: function() {
      const storage = {
        filter: this.filter
      }
      this.$emit('set-storage', storage)
    },
    // 获取具体权限（对积分管理员/公司管理员生效）
    loadAccessItemFlag: function() {
      var self = this
      this.$http('get','/integral.php/ajax_request_common/get_access_flag',{
            id: this.profile.id,
            page_name: 'employee_master'
          })
        .then(function(response) {
          if (response.status == 200) {
            var jsonData = response.data
            try {
              self.accessEnabled = jsonData
            } catch (err) {
              console.log(err)
            }
          }
        })
        .catch(function(error) {
          console.log(error)
        })
    },
    // 上传文件
    uploadFile: function(params) {
      if (!params || !params.file) {
        return false
      }
      const formData = new FormData()
      formData.append('uploader_id', this.profile.id)
      formData.append('file', params.file)
      this.$http('post','/integral.php/excel_util/import_employee_sheet', formData,'','multipart/form-data',
          // headers: {
          //   'Content-Type': 'multipart/form-data'
          // },
          {transformRequest: [
            function(data) {
              return data
            }
          ]})
        .then(response => {
          const responseData = response.data
          if (responseData.errors && responseData.errors.length > 0) {
            const messageHead = responseData.info
              ? responseData.info
              : '导入完成'
            const h = this.$createElement
            const errorGroup = [
              h('p', null, messageHead + '。但文件中存在如下问题数据：')
            ]
            errorGroup.push(
              h(
                'span',
                {
                  style: {
                    color: '#fff',
                    float: 'left',
                    width: '33%',
                    backgroundColor: 'rgb(126,148,245)',
                    padding: '5px 0 5px 10px'
                  }
                },
                '行数'
              )
            )
            errorGroup.push(
              h(
                'span',
                {
                  style: {
                    color: '#fff',
                    float: 'left',
                    width: '67%',
                    backgroundColor: 'rgb(126,148,245)',
                    padding: '5px 0'
                  }
                },
                '错误原因'
              )
            )
            for (let i = 0; i < responseData.errors.length; i++) {
              errorGroup.push(
                h(
                  'div',
                  {
                    style: {
                      float: 'left',
                      width: '33%',
                      padding: '8px 0 8px 10px',
                      borderBottom: '1px solid #ccc',
                      overflow: 'hidden'
                    }
                  },
                  '第' + responseData.errors_array[i].line + '行'
                )
              )
              errorGroup.push(
                h(
                  'div',
                  {
                    style: {
                      float: 'left',
                      width: '67%',
                      padding: '8px 0',
                      borderBottom: '1px solid #ccc',
                      overflow: 'hidden'
                    }
                  },
                  responseData.errors_array[i].msg
                )
              )
            }
            const message = h(
              'div',
              { style: { overflow: 'hidden' }},
              errorGroup
            )
            this.$alert(message, '导入结果', {
              confirmButtonText: '确定'
            })
          } else {
            this.$message({
              message: responseData.info ? responseData.info : '导入完成',
              type: responseData.status == 1 ? 'success' : 'error'
            })
          }
          if (responseData.status == 1) {
            this.loadEmployeeList()
          }
        })
        .catch(function(error) {
          console.log(error)
          return false
        })
    },
    // 下载文件
    downloadSheet: function() {
      const url =
        this.serverdomain +
        '/integral.php/excel_util/export_employee_a_sheet?site_id=' +
        this.$store.getters.site_id
      window.open(url)
    }
  },
  created() {
    this.loadBaseData()
    this.loadEmployeeList()
    if (this.profile.manager_type == 4) {
      this.accessEnabled = {
        add: 1,
        delete: 1,
        excel_import: 1,
        edit: 1
      }
    } else if (this.profile.manager_type > 1) {
      this.loadAccessItemFlag()
    }

    this.$nextTick(() => {
      document.querySelector('#app').addEventListener('click', () => {
        if (this.show3) {
          this.show3 = false
        }
      })
    })
  }
}
</script>
<style>
.el-pagination {
  text-align: center;
  margin-top: 15px;
}
.arrRotation {
  transform: rotate(180deg);
}
.treeActice {
  color: #606266;
}
.el-tree-node__content {
  height: 34px;
}
</style>
