<template>
  <div style=" background-color: #fff; padding:15px;">
    <div style="margin-top:2px; margin-bottom:15px;" class="inline-block-btn-list">
      <el-button @click="ShowRuleDetailBaseDialogVisible" type="primary" plain>基础设置</el-button>
      <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>
    </div>
    <el-table v-loading="loading" ref="multipleTable" :data="tableData" :border="false" 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_TASK" label="积分权限">
        <template slot-scope="scope">
          <el-input type="number" :autofocus="true" v-show="scope.row.is_edit" v-model="scope.row.point_limit_TASK"></el-input>
          <span v-show="!scope.row.is_edit">{{ scope.row.point_limit_TASK | pointLimitFormatter }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="point_limit_TASK" label="操作">
        <template slot-scope="scope">
          <template v-if="scope.row.is_edit">
            <el-button type="success" @click="save_point_limit(scope.row)">保存</el-button>
            <el-button type="text" @click="cancel_point_limit(scope.row)">取消</el-button>
          </template>
          <el-button v-else type="text" @click="scope.row.is_edit = !scope.row.is_edit">设置</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 :modal-append-to-body="false" :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 :modal-append-to-body="false" :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>

    <el-dialog :modal-append-to-body="false" class="attendance_group" title="绩效基础设置" :visible.sync="RuleDetailBaseDialogVisible" width="500px" top="50px">
      <el-form ref="baseformdata" :model="baseformdata" label-width="150px">
        <el-form-item label="效分转B分比例">
          <el-select v-model="baseformdata.task_point_convert" placeholder="请选择">
            <el-option label="1:1" :value="1">1:1</el-option>
            <el-option label="1:2" :value="2">1:2</el-option>
            <el-option label="1:3" :value="3">1:3</el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer"><el-button type="primary" @click="saveFormDataBase" :loading="save_loading">保 存</el-button></span>
    </el-dialog>
  </div>
</template>
<script>
import qs from 'qs';
export default {
  data() {
    const validatePointLimit = (rule, value, callback) => {
      if (isNaN(value) || value < 0 || value > 99999) {
        return callback(new Error('请填写有效的积分数值'));
      }
      callback();
    };
    return {
      baseformdata: {
        task_point_convert: 1 //按分钟，按半小时，按小时，按半天，按一天
      },
      loading1: false,
      save_loading: false,
      RuleDetailBaseDialogVisible: false,
      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
    };
  },
  filters: {
    pointLimitFormatter: function(cellValue) {
      return !isNaN(cellValue) && cellValue > 0 ? cellValue : '无限制';
    }
  },
  methods: {
    saveFormDataBase() {
      let self = this;
      let send_data = [];
      self.save_loading = true;
      send_data.push({ name: 'base_config', value: JSON.stringify(self.baseformdata) });
      this.$http('post','/integral.php/performance_work/save_task_config.html',qs.stringify({ data: send_data }),
        // headers: {
        //   'Content-Type': 'application/x-www-form-urlencoded'
        // }
      ).then(res => {
        if (res.status == 200) {
          if (res.data.code == 1000) {
            self.RuleDetailBaseDialogVisible = false;
            self.$message.success(res.data.msg);
          } else {
            self.$message.error(res.data.msg);
          }
        }
        self.save_loading = false;
      });
    },
    load_base_setting() {
      this.loading1 = true;
      const self = this;
      this.$http('/integral.php/performance_work/get_task_config',{name: 'base_config'}).then(ret => {
        self.loading1 = false;
        if (ret.status == '200') {
          const data = ret.data;
          if (data.code == 1000) {
            self.baseformdata = JSON.parse(data.data);
          }
        }
      });
    },
    ShowRuleDetailBaseDialogVisible() {
      this.load_base_setting();
      this.RuleDetailBaseDialogVisible = true;
    },
    cancel_point_limit(row) {
      row.is_edit = false;
      this.loadManagerList();
    },
    save_point_limit(row) {
      let self = this;
      this.$http('post','/integral.php/performance_work/update_task_point_limit',{employee_id: row.id,point: row.point_limit_TASK},'','',
        {transformRequest: [
          data => {
            const paramArray = new Array();
            for (const it in data) {
              paramArray.push(encodeURIComponent(it) + '=' + encodeURIComponent(data[it]));
            }
            return paramArray.join('&');
          }
        ]},
        // headers: {
        //   'Content-Type': 'application/x-www-form-urlencoded'
        // }
      ).then(function(response) {
        self.$message.success(response.data.msg);
      });

      row.is_edit = false;
    },

    handleSizeChange(val) {
      this.pageLimit = val;
      this.onFilterChanged();
    },
    saveManagerAssigns: function() {
      const 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;
          }
        });
    },
    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 (const item in this.filter) {
        const value = this.filter[item];
        if (!value) {
          continue;
        }
        const 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.map(v => {
                self.$set(v, 'is_edit', false);
                return v;
              });
            } catch (err) {
              console.log(err);
            }
          }
        });
    },
    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;
      }
      const 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 {
              const assignableList = [];
              for (const employee in jsonData.assignable_list) {
                const value = jsonData.assignable_list[employee];
                const 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;
              self.dialogAssignManagerVisible = true;
            } catch (err) {
              console.log(err);
            }
          }
        });
    },
    openAccessDialog: function(id) {
      for (const row in this.tableData) {
        const rowData = this.tableData[row];
        if (rowData.id == id) {
          this.dialogTitle = this.dialogTitleSolid + ' - ' + rowData.name;
          this.showTargetType = rowData.manager_type == 1;
          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;
              const accessValue = jsonData.access_value;
              const 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
              };
              if (jsonData.target_type_options) {
                self.targetTypeOptions = jsonData.target_type_options;
              }
              self.dialogSettingVisible = true;
            } catch (err) {
              console.log(err);
            }
          }
        });
    },
    resetAccessDialog: function() {
      const 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 {
          return false;
        }
      });
    },
    saveAccessSetting: function() {
      const dataObj = this.accessFormData;
      const formData = {};
      for (const 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 => {
            const paramArray = new Array();
            for (const it in data) {
              paramArray.push(encodeURIComponent(it) + '=' + encodeURIComponent(data[it]));
            }
            return paramArray.join('&');
          }
        ]},
        // headers: {
        //   'Content-Type': 'application/x-www-form-urlencoded'
        // }
      ).then(function(response) {
        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();
        }
      });
    }
  },
  created() {
    this.loadManagerList();
  }
};
</script>

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