<template>
  <div class="setting-outer">
    <div class="setting-container">
      <div class="setting-toolbar">
        <Row>
          <div style="width:80px;float:left;padding: 0 0 0 4px" class="leftButtonClass">
            <Button type="primary" @click.stop="addSystem">
              <Icon custom="fa fa-plus-circle fa-fw" aria-hidden="true"></Icon>添加
            </Button>
          </div>
          <div align="left" style="padding: 0 8px 0 0" class="rightButtonClass">
            <Button type="text" @click="deleSystem">
              <Icon custom="fa fa-trash fa-fw" aria-hidden="true" style="color: red"></Icon>删除
            </Button>
            <Divider type="vertical" />
            <SearchInput :value.sync="searchText"  @on-clear="clearSearch" @on-click="searchByKeyword" :width="260"/>
          </div>
        </Row>
      </div>
      <div>
        <Table
                border
                stripe
                highlight-row
                tooltip="true"
                :columns="columns"
                :data="configs"
                :loading="loading"
                :height="tableheight"
                @on-selection-change="onSelect"
        >
          <template slot-scope="{ row, index }" slot="operate">
            <Button
                    type="default"
                    @click.stop="editSystem(row, index)"
                    class="operate-button"
            >
              <Icon custom="fa fa-fw fa-edit" title="编辑"></Icon>
            </Button>
          </template>
        </Table>
      </div>
      <Modal v-model="modal" width="660" :footer-hide="true">
        <p slot="header">
          <span>
            <Icon :custom="'fa fa-' + sideComponentIcon"></Icon>
            {{ title }}</span
          >
        </p>
        <div>
          <iForm
                  :model="config"
                  :label-width="80"
                  ref="formValidate"
                  :rules="ruleValidate"
          >
            <Row>
              <iCol span="24">
                <FormItem label="名称" prop="name">
                  <iInput
                          :disabled="isDis"
                          v-model="config.name"
                          placeholder="请输入系统名称"
                  ></iInput>
                </FormItem>
              </iCol>
              <iCol span="24">
                <!-- LiuKexin 20200929 名称不是logo时 正常显示 -->
                <FormItem label="值" prop="val" v-if="config.name != 'logo'">
                  <iInput
                          v-model="config.val"
                          placeholder="请输入配置值"
                  ></iInput>
                </FormItem>
                 <!-- liukexin 20200929 名称是logo时 添加上传按钮 start -->
                <FormItem label="值" prop="val" v-if="config.name == 'logo'">
                  <iCol span="12">
                    <iInput
                      v-model="config.val"
                      placeholder="请输入配置值"
                    ></iInput>
                  </iCol>
                  <iCol span="12">
                    <Button
                      style="font-size: 12px; margin-left: 16px"
                      @click.stop="changeLogo"
                    >
                      <Icon custom="fa fa-fw fa-picture-o"></Icon>上传</Button
                    >
                  </iCol>
                </FormItem>
                <!-- liukexin 20200929 名称是logo时 添加上传按钮 end -->

              </iCol>
              <iCol span="24">
                <FormItem label="描述" prop="description">
                  <iInput v-model="config.description" type="textarea"></iInput>
                </FormItem>
              </iCol>
              <!-- Liukexin 20201228 按钮靠右 -->
              <iCol span="24" style="height:32px">
              <FormItem class="button-toolbar" style="text-align: right">
                <Button @click="reset()"><Icon custom="fa fa-refresh fa-fw"></Icon>重置</Button>
                &nbsp;&nbsp;
                <Button type="primary" @click="submit()"><Icon custom="fa fa-fw fa-save"></Icon>保存</Button>
              </FormItem>
              </iCol>

            </Row>
            <!-- LiuKexin 20200929 图片选择器 start-->
            <template>
              <input
                name="file"
                type="file"
                ref="clearFile"
                accept=".png"
                enctype="multipart/form-data"
                @change="importImageLogo"
                id="fileForExcel"
                style="display: none"
              />
            </template>
            <!-- LiuKexin 20200929 图片选择器 end-->
          </iForm>
        </div>
      </Modal>
    </div>
  </div>
</template>
<script>
  import SearchInput from '_c/search-input/searchInput'
  import { getSettings, add, dele, findConfigList,changeSetting } from '@/api/setting'
  export default {
    components: {
      SearchInput
    },
    watch: {
      searchText() {
        if(!this.searchText) {
          this.searchByKeyword()
        }
      }
    },
    data() {
      return {
        columns: [
          {
            type: 'selection',
            width: 55,
            align: 'center',
            className: 'compact-cell'
          },
          {
            title: '操作',
            width: 70,
            className: 'compact-cell',
            align: 'center',
            slot: 'operate',
            key: 'operate',
          },
          {
            title: '名称',
            width: 200,
            key: 'name',
            align: 'left',
            ellipsis: true,
            tooltip: true,
            resizable: true
          },
          {
            title: '值',
            width: 250,
            key: 'val',
            align: 'left',
            ellipsis: true,
            tooltip: true,
            resizable: true
          },
          {
            title: '描述',
            key: 'description',
            align: 'left',
            ellipsis: true,
            tooltip: true,
            resizable: true
          }
        ],
        sideComponentIcon: '',
        title: '',
        configs: [],
        oldConfig:'',
        config: {
          id: 0,
          name: '',
          val: '',
          description: ''
        },
        loading: false,
        tableheight: 0,
        modal: false,
        selection: [],
        searchText: null,
        isDis: false, //Liukexin 20200929 名称是否置灰
        file:null,
        logoUrl:'',
        ruleValidate: {
          /**xiaoying 20200717 YZJ-3931 添加长度限制和特殊字符限制 start*/
          name: [
            {
              validator: (rule, value, callback) => {
                if (value == null || value == undefined || value.trim() == '') {
                  callback(new Error('名称不能为空'))
                } else if ( value.length > 50 ) {
                  callback(new Error('名称的字数不能超过50'))
                } else {
                  let reg = /[`~!@#$%^&*()_\-+=<>?:"{}|,./;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/im
                  if (reg.test(value)) {
                    callback(new Error("不允许输入特殊字符"));
                  }
                  callback()
                }
              },
              required: true, trigger: 'blur'
            }
          ],
          val: [{
            validator: (rule, value, callback) => {
              if (value == null || value == undefined || value.trim() == '') {
                callback(new Error('值不能为空'))
              } else if ( value.length > 50 ) {
                callback(new Error('值的字数不能超过50'))
              } else {
                let reg = /[`~!#$%^&*()_\-+=<>?"{}|,;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/im
                if (reg.test(value)) {
                  callback(new Error("不允许输入特殊字符"));
                }
                callback()
              }
            },
            required: true, trigger: 'blur'
          }
            /**xiaoying 20200717 YZJ-3931 添加长度限制和特殊字符限制 end*/
          ]
        }
      }
    },
    methods: {
    /**
   * LiuKexin 20200929 点击上传触发
   */
    changeLogo() {
      document.getElementById('fileForExcel').click()
    },
      /**
     * LiuKexin 20200930 上传图片
     * */
    importImageLogo(e) {
      this.file = e.target.files[0]
      let _this = this
      if (_this.file.size / 1024 > 300) {
        _this.$Notice.warning({
          title: '提示',
          desc: '图片大小不能超过300Kb,请重新选择！',
        })
        _this.$store.state.logoUrl = this.logoUrl
        _this.file = ''
        return
      }
      if (_this.file.type.indexOf('png') > -1) {
        _this.$Notice.success({ title: '提示', desc: '图片已上传，请点击保存' })
        let reader = new FileReader()
        reader.readAsDataURL(_this.file)
        //图片转换成base64 回显
        reader.onloadend = function () {
          let newUrl = reader.result
          _this.$store.state.logoUrl = newUrl
        }
      } else {
        _this.$Notice.warning({
          title: '提示',
          desc: '图片格式只能选择png，请重新选择！',
        })
        _this.$store.state.logoUrl = this.logoUrl
        _this.file = ''
      }
    },

      searchByKeyword() {
        let parame = {
          searchText: this.searchText
        }
        findConfigList(parame).then(res => {
          if (res.data && res.data.state === 'ok') {
            this.configs = res.data.configs
          }
        })
      },
      clearSearch() {
        this.getSettings()
      },
      addSystem() {
        this.sideComponentIcon = 'plus'
        this.title = '添加'
        this.modal = true
        this.config.id = 0
        this.isDis = false //liukexin 20200929 添加名称不置灰
        this.config.name = ''
        this.config.val = ''
        this.config.description = ''
        this.$refs.formValidate.resetFields()//xiaoying 20200717 YZJ-3930 每次点击校验信息没有清空
      },
      deleSystem() {
        if (this.selection.length === 0) {
          this.$Notice.warning({ title:'提示',desc: '至少选择一项' })//xiaoying 20200717 YZJ-3929 提示类型不正确
          return
        }
        this.$Modal.confirm({
          title:'温馨提示',
          content:'删除的数据不可恢复，是否确定删除？',
          onOk: ()=>{
            let ids = this.selection.map(item => item.id)
            let data = {
              ids: ids.join(',')
            }
            dele(data).then(res => {
              if (res.data && res.data.state === 'ok') {
                this.$Notice.success({ title:'提示',desc: '删除成功' })
                this.getSettings()
              } else {
                this.$Notice.error({ title:'提示',desc: res.data.msg })
              }
            })
          }
        })
      },
      editSystem(row) {
        this.sideComponentIcon = 'edit'
        this.title = '编辑'
        this.modal = true
        this.isDis = true //liukexin 20200929 编辑名称置灰
        this.oldConfig = Object.assign({}, row)
        this.config.id = row.id
        this.config.name = row.name
        this.config.val = row.val
        this.config.description = row.description
      },
      submit() {
        this.$refs.formValidate.validate(valid => {
          if (valid) {
            add(this.config).then(res => {
              if (res.data && res.data.state === 'ok') {
                this.$Notice.success({ title:'提示',desc: res.data.ok })
                // this.getSettings()
                if (this.config.name == 'logo') {
                let param = new FormData() // 创建form对象
                param.append('file', this.file) //图片
                changeSetting(param).then((setRes) => {
                  if (setRes.data && setRes.data.state !== 'ok') {
                    this.$Notice.error({ title: '提示', desc: setRes.data.msg })
                    this.$store.state.logoUrl = this.logoUrl
                  }
                })
                }
               /** LiuKexin 20200930 保存图片 end */
               this.getSettings()
              } else {
                this.$Notice.error({ title:'提示',desc: res.data.msg })
                this.$store.state.logoUrl = this.logoUrl
              }
            })
            this.modal = false
          }
        })
      },
      reset() {
        if (this.title==='添加') {
          this.$refs.formValidate.resetFields()
        }
        if (this.title==='编辑') {
          this.config = Object.assign({}, this.oldConfig) //对重置按钮添加判断 liuyimeng 2020-03-01
          /**Liukexin 20200930 重置logo start */
          if(this.config.name == 'logo'){
            this.$store.state.logoUrl = this.logoUrl
          }
          /**Liukexin 20200930 重置logo end */

        }
      },
      onSelect(selection) {
        this.selection = selection
      },
      getSettings() {
        getSettings().then(res => {
          if (res.data && res.data.state === 'ok') {
            this.configs = res.data.configs
            this.selection = []
          }
        })
      }
    },
    mounted() {
      this.tableheight = document.body.clientHeight - 180
      this.logoUrl = this.$store.state.logoUrl
      this.getSettings()
    }
  }
</script>
<style>
  .setting-outer {
    height: 100%;
    padding: 24px;
  }
  .setting-container {
    height: 100%;
    text-align: left;
    background: #e9e9e9;
  }
  .setting-toolbar {
    border-right: 1px solid #dcdee2;
    border-right-width: 1px;
    border-right-style: solid;
    border-right-color: rgb(220, 222, 226);
    background: white;
    height: 40px;
    line-height: 39px;
  }
  .rightButtonClass .ivu-btn {
    padding: 0px;
  }
  .leftButtonClass .ivu-btn {
    padding: 0px 8px;
  }
  .operate-button {
    padding: 2px 7px;
  }
</style>
