<!-- @desc:系统参数一览  @auth:沈博  @time:2022年12月14日11:01:32 -->
<template>
  <div class="main-div" ref="mainDiv">
    <!--加载中-->
    <loading :loading="loading" v-if="!modalVisible"></loading>
    <!--按钮区-->
    <BaseIndexButtonGroup id="BaseIndexButtonGroup">
      <template #left>
        <!--    刷新    -->
        <BaseIndexButton right-button="post-refresh" ref="refresh" name="refresh"
                         @click="open($config.routeUrl.search,'leftTable')"></BaseIndexButton>
        <!--    保存    -->
        <BaseIndexButton right-button="post-save" ref="save" name="save"
                         @click="open($config.routeUrl.systemSetting.save,'leftTable',false)"></BaseIndexButton>
<!--        &lt;!&ndash;    操作日志    &ndash;&gt;-->
<!--        <BaseIndexButton right-button="role-log" ref="log" name="log"></BaseIndexButton>-->
      </template>
    </BaseIndexButtonGroup>
    <!-- 列表部分   -->
    <card ref="tableCard">
      <div style="display: flex;width: 100%;height: 100%">
        <!-- 列表部分左侧   -->
        <div style="width: 200px;">
          <DkTable
            ref="leftTable"
            :data="searchInfo"
            :height="tableHeight-30"
            :page-flag="false"
            :page-total-flag="false"
            :show-setting-flag="false"
            :freeze="false"
            :choose-flag="false"
            @current-change="currentChangeEvent($event)">
            <DkTableColumn :title="$t('parameterClassification')" field="className"
                           width="auto" :filter=false :center-flag="true"></DkTableColumn>
          </DkTable>
        </div>

        <!-- 列表部分右侧   -->
        <div style="margin-left: 5px;width:calc( 100% - 200px )">
          <DkTable
            ref="rightTable"
            :data="tableRightData"
            :height="tableHeight-30"
            :page-flag="false"
            :page-total-flag="false"
            :show-setting-flag="false"
            :freeze="false"
            :choose-flag="false">
            <DkTableColumn field="classCode" :title="$t('settingStyle')" width="100" :center-flag="true"></DkTableColumn>
            <DkTableColumn field="settingName" width="220"></DkTableColumn>
            <vxe-column show-overflow="ellipsis" field="settingValue" width="100" height="100" min-width="80"
                        class-name="setting-value-class"
                        :title="$t('settingValue')"
            >
              <template #default="{ row }">
                <!--数字类型-->
                <vxe-input v-if="row.valueKind == 'INT'" size="mini"
                           @blur="blursSettingValue(row)"
                           type="integer"
                           :readonly="!row.flgModifiable"
                           :min="row.settingCode == $config.sysCode.SYS_CODE_016 ? -1 : row.valueFormat.min"
                           :max="row.valueFormat.max" v-model="row.settingValue"></vxe-input>
                <!--文本类型-->
                <vxe-input v-if="row.valueKind == 'STR'" :maxlength="row.valueFormat.length"
                           @blur="blursSettingValue(row)"
                           :readonly="!row.flgModifiable"
                           size="mini" v-model="row.settingValue"></vxe-input>
                <!--布尔类型-->
                <i-switch size="small" v-if="row.valueKind == 'BOOL'" v-model="row.settingValue"
                          :disabled="!row.flgModifiable"
                          @on-change="changeSwitch($event,row)"></i-switch>
                <!--下拉框类型-->
                <vxe-select transfer v-if="row.valueKind == 'S-CHOICE'" v-model="row.settingValue"
                            size="mini" @change="changeOption($event,row)" :disabled="!row.flgModifiable">
                  <vxe-option v-for="item in row.valueFormat.items" :key="item.key"
                              :value="item.key" :label="item.value"></vxe-option>
                </vxe-select>

                <!--                小数-->
                <vxe-input v-if="row.valueKind == 'NUM'" size="mini"
                           @blur="blursSettingValue(row)"
                           :readonly="!row.flgModifiable"
                           type="number"
                           :min="row.settingCode == $config.sysCode.SYS_CODE_016 ? -1 : row.valueFormat.min"
                           :max="row.valueFormat.max" v-model="row.settingValue"></vxe-input>
              </template>

            </vxe-column>
            <!--            <vxe-column show-overflow="ellipsis" field="settingDefault" width="100" height="100" min-width="80"-->
            <!--                        :title="$t('settingDefault')"-->
            <!--            >-->
            <!--              <template #default="{ row }">-->
            <!--                &lt;!&ndash;数字类型&ndash;&gt;-->
            <!--                <vxe-input v-if="row.valueKind == 'INT' || row.valueKind == 'NUM'" size="mini" :disabled=true-->
            <!--                           v-model="row.settingDefault"></vxe-input>-->
            <!--                &lt;!&ndash;文本类型&ndash;&gt;-->
            <!--                <vxe-input v-if="row.valueKind == 'STR'" :disabled=true-->
            <!--                           size="mini" v-model="row.settingDefault"></vxe-input>-->
            <!--                &lt;!&ndash;下拉框类型&ndash;&gt;-->
            <!--                <vxe-input v-if="row.valueKind == 'S-CHOICE'" :disabled=true-->
            <!--                           size="mini" v-model="row.settingDefault"></vxe-input>-->
            <!--                &lt;!&ndash;布尔类型&ndash;&gt;-->
            <!--                <i-switch size="small" :disabled=true v-if="row.valueKind == 'BOOL'"-->
            <!--                          v-model="row.settingDefault"></i-switch>-->
            <!--              </template>-->
            <!--            </vxe-column>-->
            <DkTableColumn field="settingDescription" width="auto"></DkTableColumn>
          </DkTable>
        </div>
      </div>
    </card>
  </div>
</template>

<script>
//导入包
import {indexMixin} from '@/mixins'

export default {
  name: 'system-settings',
  mixins: [indexMixin],
  data() {
    return {
      // 右侧侧列表
      tableRightData: [],
      clickBackFlag: false
    }
  },
  watch: {
    searchInfo(n, o) {
      let filters = n?.filter(it => it.classType == this.$config.sysType.password_security_policy)
      if (!filters || filters.length === 0) {
        if (n) {
          n.splice(0, 0, {
            displayNo: 0,
            classType: this.$config.sysType.password_security_policy,
            className: this.$t('all')
          })
        }
      }
    }
  },
  methods: {
    // region 一览界面操作start
    /**
     * @desc   : 下拉框值变化事件
     * @author : 寇珊珊
     * @date   : 2022/3/7 17:32
     */
    changeOption(e, row) {
      // 值是否发生变化
      if (row.settingValueBack != row.settingValue) {
        this.tableRightData.forEach(it => {
          if (it.settingCode == row.settingCode) {
            // valueChangeFlg为true值发生变化
            let arraySettingValue = it.valueFormat.items.filter(iv => iv.key == e.value)
            if (arraySettingValue && arraySettingValue.length > 0) {
              it.settingValue = arraySettingValue[0].value
            }
            // 新增加的
            it.settingValueKey = e.value
            it['valueChangeFlg'] = true
          }
        })
      }
    },
    /**
     * @desc   : 开关值变化事件
     * @author : 寇珊珊
     * @date   : 2022/3/7 20:00
     */
    changeSwitch(e, row) {
      // 值是否发生变化
      if (row.settingValueBack != row.settingValue) {
        this.tableRightData.forEach(it => {
          if (it.settingCode == row.settingCode) {
            // valueChangeFlg为true值发生变化
            it.settingValue = e
            it['valueChangeFlg'] = true
          }
        })
      }
    },
    /**
     * @desc   : 文本和数字的值焦点离开事件
     * @author : 寇珊珊
     * @date   : 2022/3/6 9:46
     */
    blursSettingValue(row) {
      // 修改了原来的值
      if (row.settingValueBack != row.settingValue) {
        this.tableRightData.forEach(it => {
          if (it.settingCode == row.settingCode) {
            // valueChangeFlg为true值发生变化
            it['valueChangeFlg'] = true
          }
        })
      }
    },
    /**
     * @desc   : 左侧列表行变化事件
     * @author : 寇珊珊
     * @date   : 2022/3/5 8:51
     */
    currentChangeEvent(val) {
      if (this.clickBackFlag) {
        this.clickBackFlag = false
        return
      }
      //之前行的index
      let oldIndex
      if (val.data && val.oldValue) {
        oldIndex = val.data.map(m=>m.id).indexOf(val.oldValue.id)
      }
      let row = val.row
      if(!this.leftCurrentRow){
        this.leftCurrentRow = val.row
      }
      // 获取当前行数据
      // 值发生变化的保存 valueChangeFlg为true值发生变化
      let list = this.tableRightData.filter(it => it.valueChangeFlg == true)
      if (list && list.length > 0) {
        this.$IBMessage({content: this.$t('Q_001'), title: this.$t('systemQuestion')},
          {
            ok: () => {
              //参数校验
              this.validData().then(res => {
                if (res) {
                  // 保存-如果表里有该数据则update
                  this.saveData()
                } else if (oldIndex != null){
                  //保存校验未通过，左侧选中行还原
                  this.$nextTick(()=>{
                    this.clickBackFlag = true
                    this.$refs.leftTable.$refs.table.$children[3].$refs.table.childNodes[1].children[oldIndex].children[0].children[0].click()
                  })
                }
              })
            },
            cancel: () => {
              if (row != null) {
                //查询租户系统参数列表的数据-右侧列表
                this.getSettingData(row.classCode)
              }
            }
          })
      } else {
        if (row != null) {
          //查询租户系统参数列表的数据-右侧列表
          this.getSettingData(row.classCode)
        }
      }
    },
    // endregion

    // region 新建/编辑start
    /**
     * @desc   : 保存参数校验
     * @author : 夏常明
     * @date   : 2023/1/31 9:56
     */
    async validData() {
      let list = this.tableRightData?.copy();
      if (list && list.length > 0) {
        for (let i = 0; i < list.length; i++) {
          if (list[i].valueChangeFlg && !(list[i].valueKind == 'BOOL' || list[i].valueKind == 'S-CHOICE') && !list[i].settingValue) {
            this.$Message.warning(this.$t('W_089', {'param1': (i + 1), 'param2': "参数值"}))
            return false;
          }
        }
      } else {
        return false;
      }
      return true;
    },
    /**
     * @desc   : 系统参数发生变化时给参数赋值
     * @author : 夏常明
     * @date   : 2023/1/30 11:47
     */
    setParams() {
      let params = []
      // 值发生变化的保存 valueChangeFlg为true值发生变化
      let list = this.tableRightData.filter(it => it.valueChangeFlg == true)
      if (list && list.length > 0) {
        let message = ''
        list.forEach(it => {
          if (!(it.valueKind == 'BOOL' || it.valueKind == 'S-CHOICE') && (it.settingValue == '' || it.settingValue === undefined)) {
            message += this.$t('W_001', {'param': this.$t('settingValue')})
            return
          }
          // 输入类型 布尔类型 下拉类型的赋值
          if (it.valueKind == 'BOOL') {
            params.push({
              settingCode: it.settingCode, //参数代码
              settingValue: it.settingValue ? 1 : 0, //参数值
              ftyId: this.$store.state.user.ftyId,
            })
          } else if (it.valueKind == 'S-CHOICE') {
            params.push({
              settingCode: it.settingCode,  //参数代码
              settingValue: it.settingValueKey,//参数值
              ftyId: this.$store.state.user.ftyId,
            })
          } else {
            params.push({
              settingCode: it.settingCode,   //参数代码
              settingValue: it.settingValue, //参数值
              ftyId: this.$store.state.user.ftyId,
            })
          }
        })
      }
      this.params = params;
    },
    /**
     * @desc   : 保存系统参数值
     * @author : 夏常明
     * @date   : 2023/1/30 17:21
     */
    saveData() {
      this.loading = true;
      let params = []
      // 值发生变化的保存 valueChangeFlg为true值发生变化
      let list = this.tableRightData.filter(it => it.valueChangeFlg == true)
      if (list && list.length > 0) {
        let message = ''
        list.forEach(it => {
          // 输入类型 布尔类型 下拉类型的赋值
          if (it.valueKind == 'BOOL') {
            params.push({
              settingCode: it.settingCode, //参数代码
              settingValue: it.settingValue ? 1 : 0, //参数值
              ftyId: this.$store.state.user.ftyId,
            })
          } else if (it.valueKind == 'S-CHOICE') {
            params.push({
              settingCode: it.settingCode,  //参数代码
              settingValue: it.settingValueKey,//参数值
              ftyId: this.$store.state.user.ftyId,
            })
          } else {
            params.push({
              settingCode: it.settingCode,   //参数代码
              settingValue: it.settingValue, //参数值
              ftyId: this.$store.state.user.ftyId,
            })
          }
        })
      }
      if (params && params.length > 0) {
        this.$refs.save.$el.focus()
        this.excute(this.$service.systemService, this.$service.systemService.updateSettingValues, params).then(res => {
          if (res.code === this.$config.SUCCESS_CODE) {
            this.$Message.success(this.$t('I_001', {'param': this.$t('save')}))
            let nowRow = this.$refs['leftTable'].getCurrentRow()
            if (nowRow != null) {
              // 查询参数列表的数据-右侧列表
              this.getSettingData(nowRow.classCode)
            }
          }
          this.loading = false;
        })
      } else {
        this.loading = false;
      }
    },
    /**
     * @desc   : 获取数据
     * @author : 沈博
     * @date   : 2022年12月13日15:04:17
     */
    getData() {
      return this.excute(this.$service.commonService, this.$service.commonService.getSettingKind, {});   // 参数分类列表
    },
    /**
     * @desc   : 查询系统参数-右侧列表
     * @author : 夏常明
     * @date   : 2023/1/30 11:45
     */
    getSettingData(classCode = '') {
      // 置查询条件
      this.tableRightList = []
      // 租户系统参数列表的参数设定
      // let params = this.setSettingDataParams(classCode)
      let params = {
        settingKind: classCode,
        ftyId: this.$store.state.user.ftyId,
      }
      // 调用查询系统参数项目列表数据接口，查询右侧列表数据
      this.excute(this.$service.systemService, this.$service.systemService.getSettingValue, params).then(res => {
        if (res.code === this.$config.SUCCESS_CODE) {
          res.data.forEach(it => {

            if (it.valueFormat != undefined) {
              it.valueFormat = JSON.parse(it.valueFormat.value)
            }
            // 布尔类型
            if (it.valueKind == 'BOOL') {
              it.settingValue = it.settingValue == 1
              it.settingDefault = it.settingDefault == 1 ? this.$t('yes') : this.$t('no')
            }
            // 下拉类型
            if (it.valueKind == 'S-CHOICE') {

              //循环同步数据源key值类型 和系统参数、默认值 值类型
              it.valueFormat.items.forEach(str => {
                str.key = String(str.key);
                str.value = str.name[this.$store.state.app.local_lan]
              })
              // 当前值
              let arraySettingValue = it.valueFormat.items.filter(iv => iv.key == it.settingValue)
              // 默认值
              let arraySettingDefault = it.valueFormat.items.filter(iv => iv.key == it.settingDefault)
              if (arraySettingValue.length > 0) {
                it.settingValue = arraySettingValue[0].value
              }
              if (arraySettingDefault.length > 0) {
                it.settingDefault = arraySettingDefault[0].value
              }

            }

            // 判断是否值和原来的值发生变化
            it.settingValueBack = it.settingValue
            this.tableRightList.push(it)

          })
          this.tableRightData = this.tableRightList;
          // 参数列表的数据-右侧列表-选中第一行
          if (this.tableRightData && this.tableRightData.length > 0) {
            this.$refs.rightTable.setCurrentRow(this.tableRightData[0])
          }
        }
      })
    },
    // endregion

  },
  /**
   * @desc   : 在实例创建完成后被立即同步调用
   * @author : 寇珊珊
   * @date   : 2022/3/3 10:32
   */
  created() {
    this.pageFlag = false;
    this.initSearchFlag = true;
  },
}
</script>

<style scoped>

/deep/ .setting-value-class .vxe-cell {
  padding-left: 0 !important;
  padding-right: 0 !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center;
}

/deep/ .vxe-input--inner {
  text-align: center !important;
  padding: 0 !important;
}

/deep/ .vxe-cell {
  display: flex;
  align-items: center;
  /*padding-left: 0 !important;*/
  /*padding-right: 0 !important;*/
}

/deep/ .vxe-input--number-prev-icon {
  display: none;
}

/deep/ .vxe-input--number-next-icon {
  display: none;
}

/deep/ .vxe-input .vxe-input--extra-suffix {
  display: none;
}

/deep/ .vxe-input :hover {
  /*border: 1px solid #57a3f3 !important;*/
  /*border-radius: 2px;*/
}

/deep/ .vxe-input > input:focus {
  border-color: #57a3f3 !important;
  border-radius: 2px;
  -webkit-box-shadow: 0 0 0 1px rgba(45, 140, 240, .2) !important;
  box-shadow: 0 0 0 1px rgba(45, 140, 240, .2) !important;
}

/deep/.vxe-input--inner{
  margin-top: 1px !important;
}
</style>
