<template>
  <div class="routerWapper">
    <div class="layoutMargin layoutPadding" v-if="$route.name == 'tbls'&& $permission('000002')">
      <a-row>
        <a-col :span="3" style="border-right:1px solid #ccc;height:100%; position:relative">
          <span class="menu_header">拓展信息管理列表</span>
          <a-menu mode="vertical"  :selectedKeys="selectedKeys">
            <a-menu-item :key="k" v-show="$permission(formatPermission(item))" v-for="(item,k) in tblsLists" @click="clickMenu(k)">
              {{item}}
            </a-menu-item>
          </a-menu>
        </a-col>
        <a-col :span="18" :offset="1">
          <!-- 搜索区 -->
          <a-form class="protalForm" :form="searchForm" >
            <a-row type="flex" justify="space-between" align="middle">
               <a-col span="6" >
                <a-button class="addZiduan" v-if="$permission(formatDeletePermission())" type="primary" @click="showModal()" ghost >新增字段</a-button>
                 <div >
                  <a-modal :title="!isChangeZdy ? '新增字段':'修改字段'" v-model="visible" @cancel="handleCancel" @ok="handleOk">
                     <a-form class="protalForm" :form="form" >
                      <a-form-item label="keyCode" :label-col="{ span: 0 }" :wrapper-col="{ span: 0 }" style="height:0;visibility:hidden">
                         <a-input v-decorator="['keyCode',]" />
                      </a-form-item>
                       <a-form-item label="字段名" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
                         <a-input v-decorator="['keyName',{validateTrigger:'blur',rules: [ {required: true, message: '请输入字段名!',}]}]" />
                       </a-form-item>
                       <a-form-item  label="组件类型" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
                          <a-select  v-decorator="['compntType',{validateTrigger:'change',rules: [ {required: true, message: '请选择组件类型!',}]}]" @change="handleChange">
                            <a-select-option value="select">选择项</a-select-option>
                            <a-select-option value="date">日期</a-select-option>
                            <a-select-option value="double-1" >小数(保留一位)</a-select-option>
                            <a-select-option value="double-2">小数(保留两位)</a-select-option>
                            <a-select-option value="num">数字</a-select-option>
                            <a-select-option value="text">文本</a-select-option>
                            <a-select-option value="checkbox">多选</a-select-option>
                            <a-select-option value="radio">单选</a-select-option>
                          </a-select>
                       </a-form-item>
                      <a-form-item v-if="isShowChoose" label="选择项选项" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
                         <a-input v-decorator="['sltJson',{validateTrigger:'blur',rules: [
                                {validator: $com.validateCode}] }]"> </a-input>
                         (请输入选择项的选项并用顿号‘、’ 隔开)
                       </a-form-item>
                       <!-- 默认值需要判断组件类型 -->
                       <a-form-item v-if="form.getFieldValue('compntType')== 'select' || form.getFieldValue('compntType')== 'checkBox' || form.getFieldValue('compntType')== 'radio' " label="默认值" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
                         <a-input v-decorator="['defVal',{validateTrigger:'blur',rules: [
                                {validator: $com.validateDef}]}]"></a-input>
                          提示:组件类型为选择项、多选、或单选,必须为定义过的选项
                       </a-form-item>
                        <!-- 数字 -->
                         <a-form-item v-else-if="form.getFieldValue('compntType')== 'num'" label="默认值" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
                         <a-input v-decorator="['defVal',{validateTrigger:'blur',rules: [
                                {validator: $com.validateNum}]}]"></a-input>
                       </a-form-item>
                        <!-- 日期 -->
                        <a-form-item v-else-if="form.getFieldValue('compntType')== 'date'" label="默认值" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
                         <a-date-picker v-decorator="['defVal',]" @change="chooseDate" />
                       </a-form-item>
                        <!-- 一位 -->
                       <a-form-item v-else-if="form.getFieldValue('compntType')== 'double-1'" label="默认值" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
                         <a-input v-decorator="['defVal',{validateTrigger:'blur',rules: [
                                {validator: $com.validateNum1}]}]"></a-input>
                       </a-form-item>
                        <!-- 两位 -->
                       <a-form-item v-else-if="form.getFieldValue('compntType')== 'double-2'" label="默认值" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
                         <a-input v-decorator="['defVal',{validateTrigger:'blur',rules: [
                                {validator: $com.validateNum2}]}]"></a-input>
                       </a-form-item>
                        <a-form-item v-else label="默认值" :label-col="{ span: 5 }" :wrapper-col="{ span: 19 }">
                         <a-input v-decorator="['defVal']"></a-input>
                       </a-form-item>
                        <a-form-item label="是否支持搜索" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
                          <a-radio-group @change="onChange" v-decorator="['canSearch',{validateTrigger:'blur',rules: [ {required: true, message: '请选择是否可以支持搜索!',}]}]">
                            <a-radio value= 'true'>是</a-radio>
                            <a-radio value= 'false'>否</a-radio>
                          </a-radio-group>
                        </a-form-item>
                     </a-form>
                  </a-modal>
                </div>
              </a-col>
            </a-row>
          </a-form>
          <p class="gayLine noline"></p>
          <!-- table -->
          <a-table bordered class="portalTable" :dataSource="taskCollectList" :columns="columns" size="small" :pagination="pagination">
            <span  slot="action" slot-scope="text, record">
              <span class="actionBtn" v-if="$permission(formatDeletePermission())" @click="showDelModal(record)">删除<a-divider type="vertical" /></span>
              <a-modal title="警告" v-model="visibleDel" @ok="del(record)">
                <p>该字段可能已被使用，是否确定删除?</p>
              </a-modal>
              <span class="actionBtn" v-if="$permission(formatDeletePermission())" @click="setKey(record)">修改</span>
            </span>
          </a-table> 

        </a-col>
      </a-row>
    </div>
    <RouterWapper v-else></RouterWapper>
  </div>
</template>

<script>
export default {
  // name:'taskCollect',
  data(){
    return {
      isChangeZdy: true,
      isDate: false,
      // form: this.$form.createForm(this, { name: 'coordinated' }),
      isShowChoose: false,
      keyId: '',
      searchForm: this.$form.createForm(this), //表单验证
      streetsOptions: [{
        key: '0',
        value: '全部'
      }],
      taskCollectStatusOption: [
        {
          status: '0,1,3',
          name: '全部'
        },
        {
          status: '0',
          name: '未采集'
        },
        {
          status: '1',
          name: '已上报'
        },
        {
          status: '3',
          name: '任务结束且未上报'
        }
      ],
      taskCollectList: [], //本页列表需要展示的待上报小区列表
      columns: [
        {
          title: '字段名称',
          dataIndex: 'keyName',
          key: 'keyName',
        },
        {
          title: '组件类型',
          dataIndex: 'compntType',
          key: 'compntType',
        },
        {
          title: '选择项选项',
          dataIndex: 'sltJson',
          key: 'sltJson',
        },
        {
          title: '默认值',
          dataIndex: 'defVal',
          key: 'defVal',
        },
        {
          title: '是否支持搜索',
          dataIndex: 'canSearch',
          key: 'canSearch',
        },
        {
          title: '操作',
          dataIndex: 'action',
          key: 'action',
          scopedSlots: {
            customRender: 'action',
          },
        }
      ],
      pagination: {//分页
        pageNo: 1,
        pageSize: 10,
        total: 10,
        current: 1,
        defaultCurrent: 10,
        showQuickJumper: true,
        onChange: this.pageChange
      },
      tblsLists: [], // 全部可自定的表
      selectedKeys: [ 'tbl_community' ], //当前选中的菜单key
      targetNum: {}, //
      visible: false, //模态框状态
      // visible1: false, //模态框状态
      visibleDel: false, //模态框状态
      value: 1, //单选框选项
      row: {}, // 删除需要使用的数据
    }
  },
  created(){
    this.getList()
  },
  mounted(){
    if (this.$route.name=='tbls') {
      this.$nextTick( () => {
        this.getSearchParams()
      })
    }
  },
  methods: {
    formatPermission(item){
      let permissionNum = null
      switch (item) {
      case '小区':
        permissionNum = '00000201'
        break
      case '门牌幢':
        permissionNum = '00000202'
        break
      case '设施设备':
        permissionNum = '00000203'
        break
      case '物业企业':
        permissionNum = '00000204'
        break
      case '业主大会':
        permissionNum = '00000205'
        break
      case '业委会成员':
        permissionNum = '00000206'
        break
      case '小区管理处':
        permissionNum = '00000209'
        break
      case '小区经理':
        permissionNum = '00000210'
        break
      case '居委会信息':
        permissionNum = '00000211'
        break
      case '非居信息':
        permissionNum = '00000212'
        break
      case '非居门牌幢信息':
        permissionNum = '00000213'
        break
      default:
        break
      }
      return permissionNum
      
    },
    formatDeletePermission(){
      let deletePermissionNum = null
      switch (this.selectedKeys[0]) {
      case 'tbl_community':
        deletePermissionNum = '0000020102'
        break
      case 'tbl_building':
        deletePermissionNum = '0000020202'
        break
      case 'tbl_facilities_equipment':
        deletePermissionNum = '0000020302'
        break
      case 'tbl_prop_company':
        deletePermissionNum = '0000020402'
        break
      case 'tbl_industry_council':
        deletePermissionNum = '0000020502'
        break
      case 'tbl_ic_member':
        deletePermissionNum = '0000020602'
        break
      case 'tbl_community_amst_office':
        deletePermissionNum = '0000020902'
        break
      case 'tbl_community_manager':
        deletePermissionNum = '0000021002'
        break
      case 'tbl_residents_committees':
        deletePermissionNum = '0000021102'
        break
      case 'tbl_non_resident':
        deletePermissionNum = '0000021202'
        break
      case 'tbl_non_resident_building':
        deletePermissionNum = '0000021302'
        break
      default:
        break
      }
      return deletePermissionNum
    },
    
    //默认时间框
    chooseDate(date, dateString) { 
    },
    //展示新增模态框
    showModal() {
      this.visible = true
      this.isChangeZdy= false
      this.form.resetFields()
    },
    showDelModal(row) {
      this.visibleDel = true
      this.row= row
    },
    handleCancel(){
      this.getTaskCollectList(this.selectedKeys[0])
      this.searchForm.resetFields()
      this.isShowChoose = false
    },
    getList(){ // 获取可进行数据拓展的表
      this.$ajax.get({
        url: this.$api.GET_TBLS_LIST,
      }).then(res => {
        if (res.code === '200') { 
          this.tblsLists = res.data.content
          this.getTaskCollectList(this.selectedKeys[0])
        }
      })
    },
    //点击菜单事件
    clickMenu(e){
      this.selectedKeys=[e]
      this.searchTaskCollectList(e)
      this.$com.storeSearchParams(
        this.$route.name,
        this.pagination,
        {'selectedKey': this.selectedKeys}
      )
    },
    //分页
    pageChange(val) {
      this.pagination.pageNo = val
      this.pagination.current = val
      this.getTaskCollectList(this.selectedKeys[0])
    },
    /**
     * 从vuex中或已存储的搜索条件，判断此条件是否为当前路由的 。如果是则使用
     */
    getSearchParams(){
      const searchParams = !this.$store.state.listSearchParams?null:this.$store.state.listSearchParams[this.$route.name]
      if(!!searchParams && !!searchParams.routeName && (this.$route.name == searchParams.routeName)){
        if(!!searchParams.params){
          Object.keys(searchParams.params).forEach(elem => {
            switch (elem) {
            case 'selectedKey':
              this.selectedKey = [searchParams.params[elem]]
              break
            default:
              break
            }
          })
        }
        if(!!searchParams.pagination){
          if(!!searchParams.pagination.pageNo && searchParams.pagination.pageNo!=1){
            this.pagination.pageNo = searchParams.pagination.pageNo
          }
        }
      }
      this.getTaskCollectList(this.selectedKeys[0])
    },
    searchTaskCollectList(e){
      this.pagination.current = 1
      this.getTaskCollectList(e)
    },
    getTaskCollectList(params){ // 获取列表里面的数据
      this.$ajax.get({
        url: this.$api.GET_TBLS_KEYS,
        params: {
          tbl: params,
          pageSize: 10000,
          pageNo: this.pagination.current
        },
      }).then(res => {
        this.taskCollectList = []
        if (res.code == '200') {
          let list = this.$com.confirm(res, 'data.content', []) 
          this.pagination.total = this.$com.confirm(res, 'data.totalRows', 0)
          this.pagination.pageSize = res.data.pageSize
          this.pagination.current = res.data.page
          this.pagination.pageNo = res.data.totalPages
          for(let i=0;i<list.length;i++){
            if (list[i].compntType == 'select') {
              list[i].compntType = '选择项'
            } else if(list[i].compntType == 'date'){
              list[i].compntType = '日期'
            } else if(list[i].compntType == 'double-1'){
              list[i].compntType = '小数(保留一位)'

            }else if(list[i].compntType == 'double-2'){
              list[i].compntType = '小数(保留一位)'
            } else if(list[i].compntType == 'num'){
              list[i].compntType = '数字'
            } else if(list[i].compntType == 'text'){
              list[i].compntType = '文本'
            } else if(list[i].compntType == 'checkbox'){
              list[i].compntType = '多选'
            } else if(list[i].compntType == 'radio'){
              list[i].compntType = '单选'
            }

            if (list[i].canSearch == true) {
              list[i].canSearch = '是'
            } else if(list[i].canSearch == false){
              list[i].canSearch = '否'
            }

            this.taskCollectList.push({
              id: list[i].id,
              key: list[i].id,
              keyName: list[i].keyName,
              compntType: list[i].compntType,
              keyCode: list[i].keyCode,
              defVal: list[i].defVal,
              sltJson: list[i].sltJson,
              canSearch: list[i].canSearch
            })

            // console.log(this.taskCollectList, ' 获取的参数')
          }
        //   //
        //   // 存储当前页面列表的搜索信息
        //   //
        //   this.$com.storeSearchParams(
        //     this.$route.name,
        //     this.pagination.current,
        //     searchParms,
        //   )
        } else {
          this.$message.info(res.msg, 10)
        }
      })
    },
    handleChange(value) {
      if (value=='radio') {
        this.isShowChoose = true
        setTimeout(() => {
          this.$nextTick(() => {
            this.form.setFieldsValue({
              sltJson: '是、否'
            })
          })
        }, 0)
      }else if(value=='select' || value=='checkbox' ) {
        this.isShowChoose = true
        setTimeout(() => {
          this.$nextTick(() => {
            this.form.setFieldsValue({
              sltJson: ''
            })
          })
        }, 0)
      }else {
        this.isShowChoose = false
      }

      if (value=='date') {
        this.isDate = true
      }else{
        this.isDate = false
      }
    },
    del(){ // 删除选项
      this.$ajax.delete({
        url: this.$api.DELETE_TBLS_KEYS.replace('{id}', this.row.id)
      }).then(res => {
        if (res.code == '200') {
          this.getTaskCollectList(this.selectedKeys[0])
          this.visibleDel = false
        }
      })
    },
    setKey(row){ // 打开修改弹框
      if(row.compntType == '选择项'){
        row.compntType ='select'
      } else if (row.compntType == '日期') {
        row.compntType ='date'
      }else if (row.compntType == '小数(保留一位)') {
        row.compntType ='double-1'
      }else if (row.compntType == '小数(保留两位)') {
        row.compntType ='double-2'
      }else if (row.compntType == '数字') {
        row.compntType ='num'
      }else if (row.compntType == '文本') {
        row.compntType ='text'
      } else if(row.compntType == '多选'){
        row.compntType ='checkbox'
      } else if(row.compntType == '单选'){
        row.compntType ='radio'
      }
      if(row.canSearch == '是'){
        row.canSearch ='true'
      } else if (row.canSearch == '否') {
        row.canSearch = 'false'
      }
      if (!!row.defVal && row.compntType == 'date') {
        row.defVal = this.$moment(row.defVal)
      }
      // console.log(row, '修改的按钮')
      // 默认值的回显需要判断之前是否有

      if (!!row.sltJson && row.sltJson != null) {
        this.isShowChoose = true
        row.sltJson = !!row.sltJson ? JSON.parse(row.sltJson).join('、'): ''
        setTimeout(() => {
          this.$nextTick( () => {
            this.form.setFieldsValue({
              keyName: row.keyName,
              keyCode: row.keyCode,
              defVal: row.defVal,
              compntType: row.compntType,
              canSearch: row.canSearch,
              sltJson: row.sltJson
            })
          })
        }, 0)

      } else{
        this.isShowChoose = false
        setTimeout(() => {
          this.$nextTick( () => {
            this.form.setFieldsValue({
              keyName: row.keyName,
              keyCode: row.keyCode,
              defVal: row.defVal,
              compntType: row.compntType,
              canSearch: row.canSearch,
            })
          })
        }, 0)
      }
      this.keyId = row.id
      this.visible = true
      this.isChangeZdy = true

    },
    handleOk() { // 保存数据
      let can = true
      if ( this.form.getFieldValue('compntType') == 'select' || this.form.getFieldValue('compntType') == 'radio'){
        let arr = this.form.getFieldValue('sltJson')
        const def = this.form.getFieldValue('defVal')
        if (def==undefined || def.length<1) {
        } else {
          arr = arr.split('、')
          if (arr.indexOf(def) == -1) {
            this.form.setFields({'defVal': { value: def, errors: [new Error('默认值需为已设定的选项') ]} })
            can = false
          }else{
            can = true
          }
        }
      }

      if (this.form.getFieldValue('compntType') == 'checkbox') {
        let arr = this.form.getFieldValue('sltJson')
        let def = this.form.getFieldValue('defVal')
        if (def==undefined || def.length<1) {
        } else {
          def = this.form.getFieldValue('defVal').split('、')
          arr = arr.split('、')
          def.forEach(col => {
            if (arr.indexOf(col) == -1 ) {
              this.form.setFields({'defVal': { value: this.form.getFieldValue('defVal'), errors: [new Error('默认值需为已设定的选项') ]} })
              can = false
            }else{
              can=true
            }
          })
        }
      }

      if (can) {
        this.form.validateFields((err, values) => {
          if (!err) {
          //表单校验没有问题则发送ajx 发送数据给后台
            [values.tbl]=this.selectedKeys
            // values.tbl=this.selectedKeys[0]

            if (values.compntType == 'select' || values.compntType == 'checkbox'||values.compntType == 'radio') {
              const a = JSON.stringify(values.sltJson.split('、'))
              values.sltJson= a
            } else if(values.compntType == 'date' && values.defVal ){
              values.defVal=this.$moment(values.defVal).format('YYYY-MM-DD')
            }
            if (!values.defVal) {
              values.defVal =''
            }

            if (this.isChangeZdy) {
              // console.log(values, '修改的参数')
              this.$ajax.put({
                url: this.$api.PUT_TBLS_KEYS.replace('{id}', this.keyId),
                params: values
              }).then(res => {
                if (res.code == '200') { 
                  this.form.resetFields()
                  this.getTaskCollectList(this.selectedKeys[0])
                }
              })
            } else {
              this.$ajax.post({
                url: this.$api.POST_TBLS_KEYS,
                params: [values],
              }).then(res => {
                if (res.code== '200') {
                  this.form.resetFields()
                  this.getTaskCollectList(this.selectedKeys[0])
                }
              })
            }
            this.visible = false
          }
        })
      }
    },
    onChange(e) { // 单选裱花 
    },
  },
  beforeCreate() { // 页面进来创建form
    this.form = this.$form.createForm(this)
  },
}
</script>
<style scoped>
.menu_header{
  display: block;
  width: 100%;
  color:#1890ff;
  border-bottom:1px solid #1890ff;
  /* margin-left:-10px; */
  padding-bottom:5px;
  font-size: 16px;
  font-weight: 500;

}
.ant-menu.ant-menu-vertical.ant-menu-root.ant-menu-light{
  border-right: none;
  margin-top:8px;
  text-align: left;
}
.ant-menu.ant-menu-vertical.ant-menu-root.ant-menu-light .ant-menu-item{
  margin:0px;
}
.ant-menu.ant-menu-vertical.ant-menu-root.ant-menu-light .ant-menu-item.ant-menu-item-selected{
  border-right: 3px solid rgb(65, 145, 247);
}
.addZiduan{
 position: absolute;
 top: 0px;
 left: 10px;
}
</style>
