<template>
  <div style=" background-color: #fff; padding:15px;">

    <el-alert
      title="温馨提示："
      type="success"
      description="" style="margin-bottom:15px;">
      <p class="diy-tip">1、如果您想设置部门管理者的权限，请先到"部门信息"中指定部门管理者，然后再进行授权；</p>
      <p class="diy-tip">2、"设置公司管理"用于指定某员工账号为公司管理员，拥有对平台数据的管理和查看权限；</p>
      <p class="diy-tip">3、"设置积分专员"用于指定某员工账号为积分管理员，拥有积分操作权限，用于日常行政角色；</p>
    </el-alert>


    <div style="margin-top:2px; margin-bottom:15px;" class="inline-block-btn-list">



      <div class="gap-right-8 first-element-btn" 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 plain type="primary" @click="loadEmployeeList(3)" class="" v-show="profile.is_creator == 1">设置积分管理员
      </el-button>
      <el-button plain type="primary" @click="loadEmployeeList(2)" v-show="profile.is_creator == 1">设置公司管理
      </el-button>









    </div>
    <el-table
      v-loading="loading"
      ref="multipleTable"
      :data="tableData"
      :border="false"
      tooltip-effect="dark"
      style="width: 100%">
      <el-table-column prop="name" label="姓名"></el-table-column>
      <el-table-column prop="manager_type_name" label="用户类型"></el-table-column>
      <el-table-column prop="dept_name" label="部门"></el-table-column>
      <el-table-column prop="point_limit_B" label="积分权限" :formatter="pointLimitFormatter"></el-table-column>

      <el-table-column label="操作" width="120">
        <template slot-scope="scope">
          <el-button @click="openAccessDialog(scope.row.id)" type="text">权限设置</el-button>
        </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="dialogTitle" width="680px" :visible.sync="dialogSettingVisible" :close-on-click-modal="false"
               @close="resetAccessDialog">
      <el-form ref="accessDetailForm" :model="accessFormData" :rules="rules" @submit.native.prevent>


        <el-tabs v-model="activeName">
          <el-tab-pane label="积分权限" name="first">



            <el-row :gutter="20" style="padding-left:100px; padding-right:100px; padding-top:50px;">
            <el-form-item label="积分操作限制分值（B分）" prop="point_limit_B"  label-width="180px">
              <el-input-number v-model="accessFormData.point_limit_B" :min="0" :max="99999"></el-input-number>
            </el-form-item>

              <el-form-item label="积分操作限制分值（A分）" prop="point_limit_A"  label-width="180px" v-show="settings.point_set.indexOf('a') >= 0">
                <el-input-number v-model="accessFormData.point_limit_A" :min="0" :max="99999"></el-input-number>
              </el-form-item>

            <el-form-item label="每月奖分任务" prop="addTask" label-width="180px">
              <el-input-number v-model="accessFormData.addTask" :min="0" :max="99999"></el-input-number>

            </el-form-item>
            <el-form-item label="每月扣分任务" prop="deductTask" label-width="180px">

              <el-input-number v-model="accessFormData.deductTask" :min="0" :max="99999"></el-input-number>
            </el-form-item>



          </el-row></el-tab-pane>
          <el-tab-pane label="功能权限" name="second">


<div style="padding:50px 20px; padding-bottom:0;" v-if="showTargetType">
            <el-form-item label="积分操作对象范围" prop="target_type">
              <el-radio-group v-model="accessFormData.target_type" size="small">
                <el-radio
                  v-for="(option, key) in targetTypeOptions"
                  :label="option.value"
                  :key="key"
                  border>
                  {{ option.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
  </div>
            <el-row :gutter="20" style="padding-left:20px; padding-right:20px; padding-top:40px;" v-show="currentManagerType > 1">
            <template v-for="subModule in featureAccess">
              <el-form-item v-bind:label="subModule.name + ':'">
                <template v-for="item in subModule.items">
                  <el-checkbox
                    v-model="accessFormData.accessCheckList[item.index]"
                    border
                    size="small"
                    style="margin-right:3px;">
                    {{ item.name }}
                  </el-checkbox>
                </template>
              </el-form-item>
            </template>
          </el-row></el-tab-pane>

        </el-tabs>



      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:center;">
        <el-button @click="dialogSettingVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAccessForm('accessDetailForm')">确 定</el-button>
      </div>
    </el-dialog>







    <el-dialog
      :title="dialogAssignManager.title"
      width="660px"
      :visible.sync="dialogAssignManagerVisible"
      :close-on-click-modal="false"
      @close="resetDialogAssignManager">
      <div style="padding-left:60px; padding-bottom:10px;">
        <el-transfer
          v-model="assignedValues"
          filterable
          target-order="origin"
          :titles="dialogAssignManager.transferTitles"
          :data="assignableList">
        </el-transfer>
      </div>
      <div slot="footer" class="dialog-footer" style="text-align:center;">
        <el-button @click="dialogAssignManagerVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveManagerAssigns">确 定</el-button>
      </div>
    </el-dialog>







  </div>
</template>
<script>
  export default {
    data() {
      let validatePointLimit = (rule, value, callback) => {
        if (isNaN(value) || value < 0 || value > 99999) {
          return callback(new Error('请填写有效的积分数值'))
        }
        callback()
      }
      return {
        activeName:'first',
        profile: this.$store.getters.user_info,
        settings: this.$store.getters.system_setting,
        totalCount: 0,
        currentPage: 1,
        tableData: null,
        dialogSettingVisible: false,
        pageLimit: 10,
        filter: {
          keywords: ''
        },
        assignableList: [],
        assignedValues: [],
        dialogAssignManagerVisible: false,
        dialogAssignManager: {
          manager_type: 0,
          title: "",
          transferTitles: []
        },
        dialogTypeDepartment: {
          manager_type: 1,
          title: "部门管理",
          transferTitles: ['员工列表', '部门管理']
        },
        dialogTypeDeputy: {
          manager_type: 2,
          title: "公司管理",
          transferTitles: ['员工列表', '公司管理']
        },
        dialogTypeCompany: {
          manager_type: 3,
          title: "积分管理员",
          transferTitles: ['员工列表', '积分管理员']
        },
        loading:false,
        accessFormData: {
          id: '',
          point_limit_B: 0,
          point_limit_A: 0,
          target_type: 0,
          accessCheckList: [],
          addTask: 100,
          deductTask: 20
        },
        targetTypeOptions: [],
        featureAccess: [],
        dialogTitleSolid: '权限设置',
        dialogTitle: this.dialogTitleSolid,
        showTargetType: false,
        formLabelWidth: '105px',
        rules: {
          point_limit_B: [
            {validator: validatePointLimit, trigger: 'blur'}
          ],
          point_limit_A: [
            {validator: validatePointLimit, trigger: 'blur'}
          ],
        },
        currentManagerType: 0
      }
    },
    methods: {

      handleSizeChange(val) {
        this.pageLimit = val
        this.onFilterChanged()
      },
      saveManagerAssigns: function () {
        let params = {
          site_id: this.profile.site_id,
          manager_type: this.dialogAssignManager.manager_type,
          values: this.assignedValues.join(",")
        }
        if (this.dialogAssignManager.dept_id) {
          params.dept_id = this.dialogAssignManager.dept_id
        }
        var self = this
        this.$http('get','/integral.php/ajax_request_common/save_manager_assigns',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.loadManagerList()
            self.dialogAssignManagerVisible = false;
          }
        }).catch(function (error) {
          console.log(error)
        })
      },
      resetDialogAssignManager: function () {
        this.dialogAssignManager = {
          manager_type: 0,
          title: "",
          transferTitles: []
        }
        this.assignableList = this.assignedValues = []
      },
      onFilterChanged: function () {
        this.currentPage = 1
        this.loadManagerList()
      },
      //获取员工列表
      loadManagerList: function () {
        var self = this
        self.loading = true
        var params = {
          site_id: this.profile.site_id,
          page: this.currentPage,
          interval:this.pageLimit
        }
        for (let item in this.filter) {
          let value = this.filter[item]
          if (!value) {
            continue
          }
          let valueStr = value.toString()
          if (valueStr && valueStr.length > 0) {
            params[item] = valueStr
          }
        }
        this.$http('get','/integral.php/ajax_request_common/get_user_auth_list',params).then(function (response) {
          self.loading = false
          if (response.status == 200) {
            var jsonData = response.data
            try {
              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.loadManagerList()
      },
      pointLimitFormatter: function (row, column, cellValue) {
        return !isNaN(cellValue) && cellValue > 0 ? cellValue : "无限制"
      },
      loadEmployeeList: function (managerType, deptId) {
        deptId = deptId || 0
        switch (managerType) {
          case 1:
            this.dialogTypeDepartment.dept_id = deptId
            this.dialogAssignManager = this.dialogTypeDepartment
            break
          case 2:
            this.dialogAssignManager = this.dialogTypeDeputy
            break
          case 3:
          case 4:
            this.dialogAssignManager = this.dialogTypeCompany
            break
        }
        let params = {
          site_id: this.profile.site_id,
          manager_type: managerType
        }
        if (deptId > 0) {
          params.dept_id = deptId
        }
        var self = this
        this.$http('get','/integral.php/ajax_request_common/get_manager_transfer',params).then(function (response) {
          if (response.status == 200) {
            var jsonData = response.data
            try {
              let assignableList = []
              for (let employee in jsonData.assignable_list) {
                let value = jsonData.assignable_list[employee]
                let item = {
                  key: value.id,
                  label: value.name
                }
                if (value.id == jsonData.creator_id) {
                  item.disabled = true
                }
                assignableList.push(item)
              }
              self.assignableList = assignableList
              self.assignedValues = jsonData.assigned_values
              console.log(self.assignableList, self.assignedValues)
              self.dialogAssignManagerVisible = true
            } catch (err) {
              console.log(err)
            }
          }
        }).catch(function (error) {
          console.log(error)
        })
      },
      openAccessDialog: function (id) {
        for (let row in this.tableData) {
          let rowData = this.tableData[row]
          if (rowData.id == id) {
            this.dialogTitle = this.dialogTitleSolid + " - " + rowData.name
            this.showTargetType = rowData.manager_type == 1 ? true : false
            break
          }
        }
        this.loadAccessData(id)
      },
      //获取权限数据
      loadAccessData: function (id) {
        var self = this
        this.$http('get','/integral.php/ajax_request_common/get_access_detail',{id: id}).then(function (response) {
          if (response.status == 200) {
            var jsonData = response.data
            try {
              self.featureAccess = jsonData.access_items
              self.currentManagerType = jsonData.manager_type
              let accessValue = jsonData.access_value
              let accessCheckList = []
              if (accessValue) {
                for (let i = 0; i < accessValue.length; i++) {
                  accessCheckList.push(accessValue.charAt(i) == '1')
                }
              } else {
                for (let i = 0; i < jsonData.access_items_count; i++) {
                  accessCheckList.push(true)
                }
              }
              self.accessFormData = {
                id: id,
                point_limit_B: jsonData.point_limit_B,
                point_limit_A: jsonData.point_limit_A,
                target_type: jsonData.target_type,
                accessCheckList: accessCheckList,
                addTask: jsonData.addTask,
                deductTask: jsonData.deductTask
              }
              //console.log(self.accessFormData)
              if (jsonData.target_type_options) {
                self.targetTypeOptions = jsonData.target_type_options
              }
              self.dialogSettingVisible = true
            } catch (err) {
              console.log(err)
            }
          }
        }).catch(function (error) {
          console.log(error)
        })
      },
      resetAccessDialog: function () {
        let form = this.$refs['accessDetailForm']
        form.resetFields()
        this.accessFormData = {
          id: '',
          point_limit_B: 0,
          point_limit_A: 0,
          target_type: 0,
          accessCheckList: []
        }
      },
      submitAccessForm: function (formName) {
        var form = this.$refs[formName]
        var self = this
        form.validate((valid) => {
          if (valid) {
            if (form) {
              self.saveAccessSetting()
            }
          } else {
            //console.log('验证未通过');
            return false
          }
        })
      },
      saveAccessSetting: function () {
        let dataObj = this.accessFormData
        let formData = {}
        for (let item in dataObj) {
          if (item == 'accessCheckList') {
            let accessValue = ""
            dataObj[item].map((item) => {
              accessValue += item ? "1" : "0"
            })
            formData['access_value'] = accessValue
          } else {
            formData[item] = dataObj[item]
          }
        }
        var self = this
        this.$http('post','/integral.php/ajax_request_common/save_access_setting',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) {
          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 = "保存设置失败"
            }
          } else {
            message = "服务器出现问题"
          }
          self.$message({
            message: message,
            type: status == 1 ? 'success' : 'error'
          })
          if (status == 1) {
            self.dialogSettingVisible = false
            self.loadManagerList()
          }
        }).catch(function (error) {
          console.log(error)
        })
      }
    },
    created() {
      this.loadManagerList()
    }
  }
</script>

<style>
  .el-pagination {
    text-align: center;
    margin-top: 15px;
  }
</style>
