<template>
  <div class="container-fluid">
    <el-row class="filter_style">
      <el-col :span="24" style="padding: 0 0">
        <_BTN_FILTER :isMore="isMore" :fileName="fileName" :btnGroups="btnGroups" :tableData="tableData"/>
      </el-col>
    </el-row>
    <div>
      <_TABLE :columns="columnHeader" :tableData="dataSource" :tableHeight="400"
              :sortChange="sortChange" :rowClick="rowClick" :btnMode=true :btns="btns"
              :pageSizes="pageSizes" :currentPage=currentPage :pageSize=pageSize
              :totalCount=totalCount :queryData=this.queryData
              :checkBox=true :columnType=columnType
              :select="select" :selectAll="selectAll"
              :tableType=tableType :headerClick="headerClick"></_TABLE>
    </div>
    <_POPUP :dialogObj='dictionaryNew' @confirmBack="dictionaryNewConfirmBack" @save="saveNew"/>
    <_POPUP :dialogObj='moreDialogobj' @confirmBack="moreBack"/>
    <_POPUP :dialogObj='dictionaryUpdate' @confirmBack="dictionaryUpdateConfirmBack" @save="saveUpdate"/>
  </div>
</template>
<script>
  import _TABLE from '@/views/components/TabPagin/Table.vue'
  import _INPUT from '@/views/components/filter/InputTemp.vue'
  import _POPUP from './dictionaryPopup.vue'
  import _BTN_FILTER from '@/views/components/Screen/btn&filterTemp.vue'
  import BasePath from '@/config/BasePath'
  import api from '@/api'
  import log from '@/log'
  import { getUser } from '@/config/info'

  export default {
    mounted () {
      /** 调用初始化数据 **/
      this.init()
    },
    data () {
      return {
        /** 请求头 **/
        headers: {
          userCode: getUser().userCode,
          authToken: getUser().authToken
        },
        /** 定义按钮 **/
        btnGroups: [
          {
            name: '新增',
            className: 'btn-info',
            iconName: 'fa-plus',
            event: this.addClk
          }
        ],
        /** table **/
        tableType: '4',
        columnType: 'selection',
        currentPage: 1, // 默认当前第一页
        pageSize: 10,  // 默认每页20条数据
        pageSizes: [2, 5, 10, 20, 40, 50], // 分页数选择项
        totalCount: 0, // 表格总记录数
        isMore: false,
        columnHeader: [
          {
            value: 'typeCode',
            label: '类型',
            align: 'left'
          }, {
            value: 'typeName',
            label: '类型名称',
            align: 'left'
          }
        ],
        tableData: [],
        dataSource: [], // 当前页的数据
        btns: {
          btnArr: [
            {
              label: '修改', // 按钮的名称
              value: 'modify', // 按钮的值
              type: 'warning',
              icon: 'edit',
              functionName: this.modify // 按钮的方法
            },
            {
              label: '删除',
              value: 'del',
              type: 'danger',
              icon: 'delete',
              functionName: this.del
            }
          ],
          value: 'operation',
          label: '操作',
          width: '180px'
        },
        /** filter **/
        filmode: 0,  // 过滤方式；0:代表本地过滤，1：服务器过滤,
        filType: 1, // 过滤类型；0：单列数据过滤，1：整条数据过滤
        fileName: ['typeCode', 'typeName'],
        keyupend: false,   // 输入筛选；true：之前展示；false：之后展示
        /** 弹出层 **/
        dictionaryNew: {
          title: '新增字典数据',
          type: 'dictionaryMaintenance',
          dialogVisible: false,
          data: {
            form: {
              typeCode: '',
              typeName: '',
              tableName: '',
              fieldCode: '',
              fieldName: '',
              fieldOrder: '',
              fieldRemark: '',
              comments: '',
              userConf: '是',
              shortCode: '',
              status: '有效',
              detailEntities: [{codeName: '', codeValue: '', isDefault: 'N', remarks: '', isSystem: 'N', modificationNum: '0'}]
            }
          }
        },
        dictionaryUpdate: {
          title: '修改字典数据',
          type: 'dictionaryMaintenance',
          dialogVisible: false,
          data: {
            form: {
              rowId: '',
              typeCode: '',
              typeName: '',
              tableName: '',
              fieldCode: '',
              fieldName: '',
              fieldOrder: '',
              fieldRemark: '',
              comments: '',
              userConf: '',
              shortCode: '',
              status: '',
              detailEntities: []
            }
          }
        },
        moreDialogobj: {
          title: '查询',
          type: 'queryCondition',
          dialogVisible: false,
          data: {
            form: {
              typeCode: '',
              typeName: ''
            }
          }
        }
      }
    },
    methods: {
      /** 初始化数据方法 **/
      init () {
        api.requestJava('POST', BasePath.CODETYPE_SELECTLIST, {})
          .then((request) => {
            if (Number(request.data.code) === 200) {
              this.tableData = request.data.data
              this.queryData(this.currentPage, this.pageSize)
            } else if (Number(request.data.code) === 401) {
              this.$notify.error({ title: '查询失败', message: request.data.message })
            } else {
              throw new Error(JSON.stringify(request))
            }
          })
      .catch((err) => {
        this.$store.commit('TOGGLE_LOADING')
        let culprit = this.$route.name
        log.work(err, culprit)
      })
      },
      isMoreClk () {
        this.moreDialogobj.dialogVisible = true
      },
      moreBack (msg) {
//        let params = msg.data.form
        // api.requestJava('POST', 'common/codetype/selectOneWithDetail.do', params)
      },
      queryData (page, size) {
        // 前段分页
        this.totalCount = this.tableData.length
        this.dataSource = this.tableData.filter((u, index) => index < size * page && index >= size * (page - 1))
      }, // 分页请求
      select (selection, index) {
        if (selection[0] !== undefined) {
          //      this.sel_id = index.id
          this.sel_all = []
          for (var i in selection) {
            this.sel_all.push(selection[i].id)
          }
        } else {
          //        this.sel_id = ''
        }
      }, // 选中某1条
      selectAll (data) {
        this.sel_all = []
        for (var i in data) {
          this.sel_all.push(data[i].id)
        }
      }, // 全选
      addClk () {
        this.dictionaryNew.dialogVisible = true
      }, // 新增
      modify (index, row) {
        if (row.userConf === 'N') {
          this.$message({ type: 'info', message: '该记录不能修改!' })
          return
        }
        let params = {}
        params.typeId = row.rowId
        this.dictionaryUpdate.data.form.rowId = row.rowId
        this.dictionaryUpdate.data.form.typeCode = row.typeCode
        this.dictionaryUpdate.data.form.typeName = row.typeName
        if (row.userConf === 'Y') {
          this.dictionaryUpdate.data.form.userConf = '是'
        } else {
          this.dictionaryUpdate.data.form.userConf = '否'
        }
        if (row.status === '1') {
          this.dictionaryUpdate.data.form.status = '有效'
        } else {
          this.dictionaryUpdate.data.form.status = '停用'
        }
        api.requestJava('POST', BasePath.CODELIST_SELECT, params)
          .then((request) => {
            if (Number(request.data.code) === 200) {
              var length = request.data.data.length
              if (length === 0) {
                this.dictionaryUpdate.data.form.detailEntities = [{codeName: '', codeValue: '', isDefault: 'N', remarks: '', isSystem: 'N', modificationNum: '0'}]
              } else {
                this.dictionaryUpdate.data.form.detailEntities = request.data.data
              }
              this.dictionaryUpdate.dialogVisible = true
            } else if (Number(request.data.code) === 401) {
              this.$notify.error({ title: '查询失败', message: request.data.message })
            } else {
              throw new Error(JSON.stringify(request))
            }
          })
      .catch((err) => {
        this.$store.commit('TOGGLE_LOADING')
        let culprit = this.$route.name
        log.work(err, culprit)
      })
      }, // 修改
      del (index, row) {
        this.$confirm('确定删除此条信息吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let params = {}
          params.rowId = row.rowId
          api.requestJava('POST', BasePath.CODETYPE_DELETE, params)
          .then((request) => {
            if (Number(request.data.code) === 200) {
              this.$message({type: 'success', message: '删除成功!'})
              this.$delete(this.dataSource, index)
            } else if (Number(request.data.code) === 401) {
              this.$notify.error({ title: '删除失败', message: request.data.message })
            } else {
              throw new Error(JSON.stringify(request))
            }
          })
        .catch((err) => {
          this.$store.commit('TOGGLE_LOADING')
          let culprit = this.$route.name
          log.work(err, culprit)
        })
        }).catch(() => {
          this.$message({type: 'info', message: '已取消删除!'})
        })
      },  // 删除
      batchDelClk () {
        if (this.sel_all === undefined) {
          this.$message({type: 'info', message: '请至少选择一条记录!'})
        }
        if (this.sel_all !== undefined && this.sel_all.length > 0) {
          this.$confirm('确定删除此条信息吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$message({type: 'success', message: '根据id删除一下数据' + this.sel_all})
          }).catch(() => {
            this.$message({type: 'info', message: '已取消删除!'})
          })
        } else {
          this.$message({type: 'info', message: '请至少选择一条记录!'})
        }
      },  // 批量删除
      inputChange (val) {
        /** 搜索功能回调 **/
        let page = this.currentPage
        let size = this.pageSize
        this.dataSource = JSON.parse(val).filter((u, index) => index < size * page && index >= size * (page - 1))
      },
      dictionaryNewConfirmBack (msg) {
        this.init()
      },
      saveUpdate (msg) {
        let params = {}
        params.rowId = this.dictionaryUpdate.data.form.rowId
        params.typeCode = this.dictionaryUpdate.data.form.typeCode
        params.typeName = this.dictionaryUpdate.data.form.typeName
        params.tableName = this.dictionaryUpdate.data.form.tableName
        params.fieldCode = this.dictionaryUpdate.data.form.fieldCode
        params.fieldName = this.dictionaryUpdate.data.form.fieldName
        params.fieldOrder = this.dictionaryUpdate.data.form.fieldOrder
        params.fieldRemark = this.dictionaryUpdate.data.form.fieldRemark
        params.comments = this.dictionaryUpdate.data.form.comments
        params.shortCode = this.dictionaryUpdate.data.form.shortCode
        if (this.dictionaryUpdate.data.form.userConf === '是') {
          params.userConf = 'Y'
        } else {
          params.userConf = 'N'
        }
        if (this.dictionaryUpdate.data.form.status === '有效') {
          params.status = '1'
        } else {
          params.status = '0'
        }
        params.deletedFlag = 0
        api.requestJava('POST', BasePath.CODETYPE_UPDATE, params)
          .then((request) => {
            if (Number(request.data.code) === 200) {
              let params1 = []
              var length = this.dictionaryUpdate.data.form.detailEntities.length
              for (var i = 0; i < length; i++) {
                var jsontemp = {}
                jsontemp.typeId = this.dictionaryUpdate.data.form.rowId
                jsontemp.typeCode = this.dictionaryUpdate.data.form.typeCode
                jsontemp.codeName = this.dictionaryUpdate.data.form.detailEntities[i].codeName
                jsontemp.codeValue = this.dictionaryUpdate.data.form.detailEntities[i].codeValue
                jsontemp.isDefault = this.dictionaryUpdate.data.form.detailEntities[i].isDefault
                jsontemp.isSystem = this.dictionaryUpdate.data.form.detailEntities[i].isSystem
                jsontemp.modificationNum = this.dictionaryUpdate.data.form.detailEntities[i].modificationNum
                jsontemp.remarks = this.dictionaryUpdate.data.form.detailEntities[i].remarks
                jsontemp.deletedFlag = this.dictionaryUpdate.data.form.detailEntities[i].deletedFlag
                params1.push(jsontemp)
              }
              api.requestJava('POST', BasePath.CODELIST_INSERT, params1)
            .then((request) => {
              this.dictionaryUpdate.data.form.detailEntities = [{codeName: '', codeValue: '', isDefault: 'N', remarks: '', isSystem: 'N', modificationNum: '0'}]
            })
              this.$message({ type: 'success', message: '保存成功!' })
              this.dictionaryUpdate.dialogVisible = false
              this.dictionaryNewConfirmBack(this.dictionaryNew)
            } else if (Number(request.data.code) === 401) {
              this.$notify.error({ title: '新增失败', message: request.data.message })
            } else {
              throw new Error(JSON.stringify(request))
            }
          })
      },
      saveNew (msg) {
        let params = {}
        params.typeCode = this.dictionaryNew.data.form.typeCode
        params.typeName = this.dictionaryNew.data.form.typeName
        params.tableName = this.dictionaryNew.data.form.tableName
        params.fieldCode = this.dictionaryNew.data.form.fieldCode
        params.fieldName = this.dictionaryNew.data.form.fieldName
        params.fieldOrder = this.dictionaryNew.data.form.fieldOrder
        params.fieldRemark = this.dictionaryNew.data.form.fieldRemark
        params.comments = this.dictionaryNew.data.form.comments
        params.shortCode = this.dictionaryNew.data.form.shortCode
        if (this.dictionaryNew.data.form.userConf === '是') {
          params.userConf = 'Y'
        } else {
          params.userConf = 'N'
        }
        if (this.dictionaryNew.data.form.status === '有效') {
          params.status = '1'
        } else {
          params.status = '0'
        }
        params.deletedFlag = 0
        params.modificationNum = 0
        params.detailEntities = this.dictionaryNew.data.form.detailEntities
        api.requestJava('POST', BasePath.CODETYPE_INSERT, params)
          .then((request) => {
            if (Number(request.data.code) === 200) {
              api.requestJava('POST', BasePath.CODELIST_INSERT, request.data)
                .then((request) => {
                  console.log('插入多条细表数据')
                  console.log(request.data)
                  this.dictionaryNew.data.form.detailEntities = [{codeName: '', codeValue: '', isDefault: 'N', remarks: '', isSystem: 'N', modificationNum: '0'}]
                })
              this.$message({ type: 'success', message: '保存成功!' })
              this.dictionaryNew.dialogVisible = false
              this.dictionaryNewConfirmBack(this.dictionaryNew)
            } else if (Number(request.data.code) === 401) {
              this.$notify.error({ title: '新增失败', message: request.data.message })
            } else {
              throw new Error(JSON.stringify(request))
            }
          })
      },
      dictionaryUpdateConfirmBack (msg) {
        let data = msg.data.form
        let paraminfo = {}
        paraminfo.rowId = data.rowId
        paraminfo.userCode = data.userCode
        paraminfo.userName = data.userName
        paraminfo.attrFlag = '0'
        paraminfo.companyId = data.company.id
        paraminfo.divisionId = data.department.id
        paraminfo.password = data.password
        paraminfo.email = data.email
        paraminfo.personId = data.personId
        paraminfo.contactPhone = data.tel
        paraminfo.mobile = data.phone
        if (data.status === true) {
          paraminfo.status = '1'
        } else {
          paraminfo.status = '0'
        }
        if (data.isLogIn === true) {
          paraminfo.loginFlag = '1'
        } else {
          paraminfo.loginFlag = '0'
        }
        paraminfo.remark = data.remark
        api.requestJava('POST', 'system/user/selectList.do', {}, { 'headers': this.headers })
          .then((request) => {
            if (Number(request.data.code) === 200) {
              console.log(request.data)
              this.$router.go(0)
            } else if (Number(request.data.code) === 401) {
              this.$notify.error({ title: '修改失败', message: request.data.message })
            } else {
              throw new Error(JSON.stringify(request))
            }
          })
      },
      sortChange (msg) {},
      rowClick (msg) {},
      headerClick (column, event) {}
    },
    components: {
      _TABLE,
      _INPUT,
      _POPUP,
      _BTN_FILTER
    }
  }
</script>
