<!-- 用户权限配置 -->
<template>
  <div class="app-container">
    <!-- 添加 -->
    <el-form inline ref="addForm" :rules="addFormRules" :model="addFormItem" label-width="80px">
      <!-- 用户名称 -->
      <el-form-item label="选择用户" prop="customerId">
        <el-select filterable size="small" v-model="addFormItem.customerId" placeholder="请选择用户列表">
          <el-option
            v-for="(item,index) in customerList"
            :key="index"
            :value="item['value']"
            :label="item.label"
          />
        </el-select>
      </el-form-item>
      <!-- 模块 -->
      <el-form-item size="small" label="模块" prop="module">
        <hook-input
          size="small"
          inputStyle="width:194px"
          placeholder="配置模块"
          v-model="addFormItem.module"
          :inputType="moduleObj.inputType"
          :keyList="moduleObj.keyList"
          @change="getKeyList"
        />
      </el-form-item>
      <!-- 配置项 -->
      <el-form-item size="small" label="配置项" prop="key">
        <hook-input
          size="small"
          inputStyle="width:194px"
          placeholder="配置项"
          v-model="addFormItem.key"
          :inputType="keyObj.inputType"
          :keyList="keyObj.keyList"
          @change="getValueList"
        />
      </el-form-item>
      <!-- 配置值 -->
      <el-form-item label="配置值" prop="value">
        <hook-input
          size="small"
          inputStyle="width:194px"
          placeholder="配置值"
          v-model="addFormItem.value"
          :inputType="valueObj.inputType"
          :keyList="valueObj.keyList"
        />
        <el-button size="mini" type="primary" @click="handleAddConfig">添加</el-button>
      </el-form-item>
    </el-form>
    <!-- 搜索 -->
    <el-form inline ref="searchFormItem" :model="searchFormItem" label-width="80px">
      <!-- 用户名称 -->
      <el-form-item label="查询用户" prop="customerName">
        <el-input
          size="small"
          v-model="searchFormItem.customerName"
          clearable
          @clear="handleSearch"
          style="width:194px"
        />
        <el-button size="mini" type="primary" @click="handleSearch">查询</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格 -->
    <el-table :data="table.body" style="width: 100%">
      <el-table-column type="index" width="50" />
      <el-table-column prop="cusmerName" label="客户名称" />
      <el-table-column label="模块">
        <template slot-scope="scope">
          <span>{{scope.row['module']&&scope.row['module']['value']}}</span>
        </template>
      </el-table-column>
      <el-table-column label="配置项">
        <template slot-scope="scope">
          <span>{{scope.row['type']&&scope.row['type']['value']}}</span>
        </template>
      </el-table-column>
      <el-table-column label="配置值">
        <template slot-scope="scope">
          <span>{{valueName(scope.row)}}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <span>{{scope.row['status']&&scope.row['status']['value']}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="startTime" label="生效日期" />
      <el-table-column prop="endTime" label="失效日期" />
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 修改 -->
    <el-dialog title="修改" :visible.sync="dialogVisible">
      <el-form v-if="active" :model="modifyFormItem" label-width="80px">
        <el-form-item label="客户名称">
          <el-input v-model="active.cusmerName" disabled />
        </el-form-item>
        <el-form-item label="模块">
          <el-input v-model="active.module['value']" disabled />
        </el-form-item>
        <el-form-item label="配置项">
          <el-input v-model="active.type['value']" disabled />
        </el-form-item>
        <el-form-item label="配置值">
          <hook-input
            v-model="modifyFormItem.value"
            :inputType="modifyFormItem.valueType"
            width="100%"
            :keyList="modifyFormItem.valueList"
            size="small"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleChange">确 定</el-button>
      </div>
    </el-dialog>

    <pagination
      v-show="page.total>0"
      :total="page.total"
      :page.sync="page.current"
      :limit.sync="page.size"
      @pagination="getConfigSearch"
    />
  </div>
</template>

<script>
import {
  addConfig,
  deleteConfig,
  getCustomerList,
  getCustomerDict,
  getConfigSearch
} from "@/api/system/authority";
// 克隆方法
import {
  deepClone
} from "@/utils/index";

import hookInput from "./hook-input";

export default {
  data() {
    return {
      moduleObj: {
        inputType: "SELECT",
        keyList: []
      },
      keyObj: {
        inputType: "TEXT",
        keyList: []
      },
      valueObj: {
        inputType: "TEXT",
        keyList: []
      },
      addFormItem: {
        customerId: "",
        module: "",
        key: "",
        value: ""
      },
      addFormRules: {
        customerId: [
          { required: true, message: "请选择用户", trigger: "blur" }
        ],
        module: [{ required: true, message: "请选择模块", trigger: "blur" }],
        key: [{ required: true, message: "请选择配置项", trigger: "blur" }],
        value: [
          { required: true, message: "请补充完整配置值", trigger: "blur" }
        ]
      },
      modifyFormItem: {
        value: "",
        valueType: "TEXT",
        valueList: []
      },
      searchFormItem: {
        customerName: undefined,
        project: undefined
      },
      customerList: [],
      projectList: [],
      workList: [],
      keyList: [],
      keyType: "TEXT",
      dialogVisible: false,
      table: {
        head: [],
        body: []
      },
      page: {
        total: 0,
        current: 1,
        size: 10
      },
      active: undefined,
      accountList: [
        {}
      ]
    };
  },
  created() {},
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.getProjectList();
      this.getConfigSearch();
      this.getCustomerList();
    },
    // 配置值名字
    valueName(name) {
      let names = name['value']['value'] || name['value']
      return names === 'UNLIMITED' ? '不限' : names
    },
    // 获取用户下拉选项
    getCustomerList() {
      getCustomerList()
        .then(res => {
          let { data, code, message } = res;
          if (code !== 200) {
            this.$message.error(message);
            return;
          }
          data = data.map(item => {
            let { name: label, value } = item;
            return {
              value,
              label
            };
          });
          this.customerList = data;
        })
        .catch(error => {
          this.$message.error(error.message);
        });
    },
    // 搜索
    handleSearch() {
      this.page.current = 1;
      this.getConfigSearch();
    },
    // 获取用户配置列表
    getConfigSearch() {
      let { current, size } = this.page;
      let { customerName, project: module } = this.searchFormItem;
      getConfigSearch({ current, size, customerName, module })
        .then(res => {
          let { data, code, message } = res;
          if (code !== 200) {
            this.$message.error(message);
            return;
          }
          let { current, total, records } = data;
          Object.assign(this.page, { current, total });
          this.table.body = records;
        })
        .catch(error => {
          this.$message.error(error.message);
        });
    },
    // 获取模块列表
    getProjectList() {
      let parentId = "-1";
      this.$set(this.addFormItem, "key", "");
      this.$set(this.addFormItem, "value", "");
      this.handleGetCustomerDict({ parentId })
        .then(res => {
          let { list } = res;
          this.moduleObj.keyList = list;
        })
        .catch(error => {
          this.$message.error(error.message);
        });
    },
    // 获取配置项接口
    getKeyList() {
      let {
        moduleObj: { keyList },
        addFormItem: { module: key }
      } = this;
      this.$set(this.addFormItem, "key", "");
      this.$set(this.addFormItem, "value", "");
      let parent = this.getParent(keyList, key);
      let { id: parentId, inputType } = parent;
      this.handleGetCustomerDict({ parentId })
        .then(res => {
          let { list, inputType } = res;
          this.keyObj.keyList = list;
          this.keyObj.inputType = inputType;
        })
        .catch(error => {
          this.$message.error(error.message);
        });
    },
    // 获取配置值列表
    getValueList() {
      let {
        keyObj: { keyList },
        addFormItem: { key }
      } = this;
      let { module } = this.addFormItem
      this.$set(this.addFormItem, "value", "");
      let parent = module === 'LICENSED_MEDIA_ON_DEMAND' ? keyList[0] : this.getParent(keyList, key);
      if(!parent) { return }
      let { id: parentId, inputType } = parent;
      this.keyType = inputType;
      this.valueObj.inputType = inputType;
      if (inputType !== "SELECT") return;
      this.handleGetCustomerDict({ parentId })
        .then(res => {
          let { list, inputType } = res;
          this.valueObj.keyList = list;
          this.valueObj.inputType = inputType;
        })
        .catch(error => {
          this.$message.error(error.message);
        });
    },
    // 获取修改配置值列表
    getModifyKeyList(row) {
      let { type: { code: parentCode } = { code: null } } = this.active;
      if (this.active.module && this.active.module.code === "LICENSED_MEDIA_ON_DEMAND") {
        parentCode = row.type.code.split(',')[0]
      }
      this.handleGetCustomerDict({ parentCode })
        .then(res => {
          let { list, inputType } = res;
          this.modifyFormItem.valueList = list;
          this.modifyFormItem.valueType = inputType;
        })
        .catch(error => {
          this.$message.error(error.message);
        });
    },
    // 新增
    handleAddConfig() {
      this.$refs["addForm"].validate(valid => {
        if (!valid) return;
        let { customerId, module, key, value } = deepClone(this.addFormItem);
        if (module === 'LICENSED_MEDIA_ON_DEMAND') {
          key = key.join(',')
        }
        this.addConfig({ customerId, module, key, value });
      });
    },
    // 修改
    handleChange() {
      let {
        customerId,
        module: { code: module },
        type: { code: key }
      } = this.active;
      let { value } = this.modifyFormItem;
      this.addConfig({ customerId, module, key, value });
    },
    // 新增&修改
    addConfig({ customerId, module, key, value }) {
      addConfig({ customerId, module, key, value })
        .then(res => {
          let { data, code, message } = res;
          if (code !== 200) {
            this.$message.error(message);
            reject(new Error(message));
          }
          this.dialogVisible = false;
          this.getConfigSearch();
        })
        .catch(error => {
          reject(new Error(message));
        });
    },
    //  修改
    handleEdit(index, row) {
      this.modifyFormItem.valueList = [];
      this.dialogVisible = true;
      this.active = deepClone(row);
      this.modifyFormItem.value = row["value"]["value"] || row["value"];
      this.getModifyKeyList(row);
    },
    // 删除
    handleDelete(index, row) {
      let { configId } = row;
      deleteConfig({ configId })
        .then(res => {
          let { data, code, message } = res;
          if (code !== 200) {
            this.$message.error(message);
            reject(new Error(message));
          }
          this.getConfigSearch();
        })
        .catch(error => {
          reject(new Error(message));
        });
    },
    // 系统权限配置 list 查询
    handleGetCustomerDict({ parentId, parentCode }) {
      return new Promise((resolve, reject) => {
        getCustomerDict({ parentId, parentCode })
          .then(res => {
            let { data, code, message } = res;
            if (code !== 200) {
              this.$message.error(message);
              reject(new Error(message));
            }
            let { list, inputType } = data;
            list = list.map(item => {
              let { code, name } = item;
              item["value"] = code;
              item["label"] = name;
              return item;
            });
            resolve({ list, inputType });
          })
          .catch(error => {
            reject(new Error(message));
          });
      });
    },
    // 获取 id
    getParent(arr, value) {
      let active = arr.find(item => {
        return item.code === value;
      });
      return active;
    },
    // 表单重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
  computed: {},
  components: {
    hookInput
  }
};
</script>

<style scoped lang="less">
</style>