// 小区列表
<template>
  <div class="routerWapper">
    <div v-if="$route.path == '/houseData/basicInfo'" class="layoutMargin layoutPadding">
      <a-form :form="form" class="protalForm" >
        <a-row class="formItem" type="flex" align='top' :gutter="18">
          <a-col span="8">
            <a-form-item label="小区名称" class="formItem" :label-col="{span:10}" :wrapper-col="{span:14}">
              <a-input placeholder="请输入查询内容" v-decorator="['stNameFrst_l']" />
            </a-form-item>
          </a-col>
          <a-col span="8" >
            <a-form-item label="小区地址" class="formItem" :label-col="{span:10}" :wrapper-col="{span:14}">
              <a-input placeholder="请输入查询内容" v-decorator="['addrFrst_l']" />
            </a-form-item>
          </a-col>
          <a-col span="8" >
            <a-form-item label="房办" class="formItem" :label-col="{span:10}" :wrapper-col="{span:14}">
              <a-select showSearch allowClear placeholder="请选择查询内容" v-decorator="['c.hoId']" @change="handleChangefb">
                <a-select-option v-for="(item) in hos" :key="item.hoId" :value="item.cspName+'#'+item.hoId">{{ item.hoName }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col span="8">
            <a-form-item label="物业公司名称" class="formItem" :label-col="{span:10}" :wrapper-col="{span:14}">
              <a-select showSearch allowClear placeholder="请选择查询内容" v-decorator="['c.cspId'] " @change="changeWy">
                <a-select-option v-for="(item) in wuye" :key="item.cspId" :value=" item.cspName+'#'+item.cspId">{{ item.cspName }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col span="8" >
            <a-form-item label="街道名称" class="formItem" :label-col="{span:10}" :wrapper-col="{span:14}">
              <a-select showSearch allowClear placeholder="请选择查询内容" v-decorator="['c.streetId']"  @change="changeStreet">
                <a-select-option v-for="(item) in street" :key="item.streetId" :value="item.strName+'#'+item.streetId">{{ item.strName }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col span="8">
            <a-form-item label="成立业主大会" class="formItem" :label-col="{span:10}" :wrapper-col="{span:14}">
              <a-select allowClear placeholder="请选择查询内容" v-decorator="['isHoc']" @change="changeIsHoc">
                <a-select-option value="false">否</a-select-option>
                <a-select-option value="true">是</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col span="8">
            <a-form-item label="小区性质" class="formItem" :label-col="{span:10}" :wrapper-col="{span:14}">
              <a-select
                v-decorator="['stKind_in']"
                mode="multiple"
                style="width: 100%"
                placeholder="请选择小区性质（多选）"
                @change="changeType"
                allowClear
              >
                <a-select-option v-for="i in typeList" :key="i.key">{{i.name}}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <!-- 动态搜索条件 -->
          <template v-if="customKeyEnable">
            <a-col span="8"  v-for="i in searchList" :key="i.id" >
              <a-form-item :label="i.keyName" class="formItem" :label-col="{span:10}" :wrapper-col="{span:14}">
                <a-select @change="handleChangeZdy(i.keyCode,$event)" v-if="i.compntType == 'select' || i.compntType == 'radio'" showSearch allowClear placeholder="请选择查询内容" v-decorator="[i.keyCode]">
                  <a-select-option v-for="(item) in JSON.parse(i.sltJson)" :key="item" :value="item">{{ item }}</a-select-option>
                </a-select>
                <a-select @change="handleChangeZdy(i.keyCode,$event)" mode="multiple" v-else-if="i.compntType =='checkbox'"  placeholder="请选择查询内容(多选)" v-decorator="[i.keyCode]">
                  <a-select-option v-for="(item) in JSON.parse(i.sltJson)" :key="item" :value="item">{{ item }}</a-select-option>
                </a-select>
                <a-date-picker @change="handleChangeZdy(i.keyCode,$event)" v-else-if="i.compntType =='date'"  v-decorator="[i.keyCode]"  />
                <a-input v-else-if="i.compntType =='num'" type="tel" placeholder="请输入查询内容" v-decorator="[i.keyCode]" />
                <a-input v-else placeholder="请输入查询内容" v-decorator="[i.keyCode]" />
              </a-form-item>
            </a-col>
          </template>
          <!-- 功能按钮区 -->
          <a-col span="24" class="algin-right">
            <a-button  @click="exportList">导出数据</a-button>
            <a-button @click="reset">重置</a-button>
            <a-button type="primary" @click="search">搜索</a-button>
          </a-col>
        </a-row>
      </a-form>
        <!-- <p class="gayLine noline" /> -->
        <div class="portalTableOperates">
          <tableAndMut ref="childTab" :tableData="tableData" :pagination="pagination" :tbl="tbl" />
        </div>
    </div>
    <RouterWapper v-else></RouterWapper>
  </div>
</template>

<script>
export default {
  name:'basicInfo',
  data() {
    return {
      customKeyEnable:false,    // cookie里存的是否开启自定义字段
      typeList:[                //小区性质的数据
        {
          name:'商品房',
          key:'01'
        },
        {
          name:'动迁房',
          key:'02'
        },
        {
          name:'共有产权保障房',
          key:'03'
        },
        {
          name:'售后房',
          key:'04'
        },
        {
          name:'直管公房',
          key:'05'
        },
        {
          name:'混合',
          key:'06'
        },
        {
          name:'系统公房',
          key:'07'
        },
        {
          name:'集体土地集资房',
          key:'08'
        },
        {
          name:'军产',
          key:'09'
        },
        {
          name:'私产',
          key:'10'
        },
        {
          name:'公租房',
          key:'11'
        },

      ],
      tbl:'tbl_community',     // 当前表名,
      searchList:[],           // 动态渲染的搜索列表
      keyCodeList:[],          // 动态搜索的keycode列表
      searchParams:{},         // 搜索的列表
      searchForm:{},
      street:[],               // 街道数据
      hos: [],                 // 房办数据
      wuye: [],                // 物业数据
      columns: [               //表格展示的列
        {
          title: '小区名称',
          dataIndex: 'stNameFrst',
          key: 'stNameFrst'
        },
        {
          title: '小区地址',
          dataIndex: 'addrFrst',
          key: 'addrFrst'
        }, {
          title: '房管办',
          dataIndex: 'hoName',
          key: 'hoName'
        },
        {
          title: '街道',
          dataIndex: 'strName',
          key: 'strName'
        },
        {
          title: '小区性质',
          dataIndex: 'stKind',
          key: 'stKind'
        },   {
          title: '小区类型',
          dataIndex: 'sectType',
          key: 'sectType'
        },   {
          title: '物业服务企业',
          dataIndex: 'cspName',
          key: 'cspName'
        },   {
          title: '小区管理处',
          dataIndex: 'csName',
          key: 'csName'
        },
        {
          title: '是否成立业主大会',
          dataIndex: 'hocId',
          key: 'hocId'
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 160,
          scopedSlots: {
            customRender: 'action'
          }
        }
      ],
      pagination: {            // 分页信息
        pageNo: 1,
        pageSize: 20,
        current: 1,
        defaultCurrent: 1,
        defaultPageSize:20,
        showQuickJumper: true,
        onChange: this.pageChange,
        showSizeChanger:true,
        onShowSizeChange:this.showSizeChange,
        pageSizeOptions:['10','20','50','100'],
        total: 0, // 小区总数
        showTotal: total => `总条数: ${total}`,
        totStCnstArea: '', // 房屋总面积 平方米
        totUnits: '', // 总门牌数  幢
        totHous: '', // 总分户数   户
      },
      tableData:[],
    }
  },
  beforeCreate() {    // 页面进来创建form
    this.form = this.$form.createForm(this)
  },
  created () {   // 进页面获取数据
    this.customKeyEnable=this.$cookie.get('customKeyEnable')
    this.getHos()
    this.getWy()
    this.getStreet()
  },
  mounted(){
    if(this.$route.name == 'basicInfo'){
      this.$nextTick(function () {
        // setTimeout(() => {
        this.getSearchParams()
        // }, 0)
      })
    }
  },
  methods:{
    pageChange(page, pageSize){        //分页切换
      this.pagination.pageNo = page
      this.pagination.current = page
      this.getList()
    },
    showSizeChange(current, size) {   //每页条数切换
      this.pagination.pageNo = 1
      this.pagination.current = 1
      this.pagination.pageSize = size
      this.getList()
    },
    reset(){  // 重置表单
      this.form.resetFields()
      this.pagination.pageNo = 1
      this.pagination.current = 1
      this.pagination.pageSize = 20
      this.getList()
    },
    search() {    // 搜索按钮
      this.pagination.current = 1
      this.pagination.pageNo = 1
      //需要发送ajax
      this.getList()
    },
    changeWy(value){        // 切换物业
      let query=JSON.parse(JSON.stringify(this.$route.query))
      query={id:'',name:''}
      this.$router.push({path:'basicInfo',query:query})
      this.form.setFieldsValue({
        'c.cspId':value
      })
      this.search()
    },
    changeStreet(value) {     // 切换街道
      this.form.setFieldsValue({
        'c.streetId':value
      })
      this.search()
    },
    changeIsHoc(value) {         // 切换是否成立业主大会
      this.form.setFieldsValue({
        'isHoc':value
      })
      this.search()
    },
    changeType(val) {            // 切换小区性质
      this.form.setFieldsValue({
        'stKind_in':val
      })
      this.getList()
    },
    handleChangefb(value) {           //切换房办
      this.form.setFieldsValue({
        'c.hoId':value
      })
      this.search()
    },
    handleChangeZdy(i,e){       // 自定义字段 - 搜索条件的 change
      if (Object.prototype.toString.call(e)== '[object Array]') {
        e = e.join(',')
      } else if (Object.prototype.toString.call(e)== '[object Object]') {
        e = this.$moment(e).format('YYYY-MM-DD')
      }
      this.form.setFieldsValue({         // 传入的i 是i.keyCode   将form表单设置成最新的值
        i:e
      })
      setTimeout(()=>{                    // 延时器,去掉会拿不到最新的value
        this.getList()
      },0)
    },
    getList(){    // 获取小区数据
      //处理动态的搜索条件,耦合到搜索列表
      let obj  = {}
      this.keyCodeList.forEach(item => {
        let value  = !this.form.getFieldValue(item)? '':this.form.getFieldValue(item)
        if (Object.prototype.toString.call(value)== '[object Array]') {   //如果是数组
          value = value.join(',') 
        }else if(Object.prototype.toString.call(value) === '[object Object]'){
          value = this.$moment(value).format('YYYY-MM-DD')
        }
        this.$set(obj,item,value)
      })
      let isHocId = {}
      if (this.form.getFieldValue('isHoc')) {                       //判断是否有业主大会,   处理入参为 hocId_ne 还是 hocId
        if (this.form.getFieldValue('isHoc') != 'true') {
          isHocId = {
            hocId:'null'
          }
        } else {
          isHocId = {
            hocId_ne:'null'
          }
        }
      }
      let searchParams = Object.assign({},{
        'stNameFrst_l': this.form.getFieldValue('stNameFrst_l')|| '',
        'addrFrst_l': this.form.getFieldValue('addrFrst_l')|| '',
        'c.cspId': !this.form.getFieldValue('c.cspId')?'':this.form.getFieldValue('c.cspId').split('#')[1],
        'c.hoId': !this.form.getFieldValue('c.hoId')?'':this.form.getFieldValue('c.hoId').split('#')[1],
        'c.streetId': !this.form.getFieldValue('c.streetId')?'':this.form.getFieldValue('c.streetId').split('#')[1],
        'stKind_in': !this.form.getFieldValue('stKind_in')?'':this.form.getFieldValue('stKind_in').join(','),
        'sectType_in': '1',
        'c.createTime_desc':'desc'
      },obj,isHocId)// 融合obj 和isHocId 到入参
      if (this.$route.query.id  && this.$route.query.id != '') {
        // 如果query的id不为空,则回显,并根据id搜索
        this.form.setFieldsValue({'c.cspId':this.$route.query.name+'#'+this.$route.query.id})
        searchParams = Object.assign(searchParams,{},{'c.cspId':this.$route.query.id ,'c.createTime_desc':'desc'})
      }
      this.searchParams = searchParams
      this.$ajax.get({
        url: this.$api.GET_BASIC_LIST,
        params:Object.assign({},searchParams,{
          pageSize:this.pagination.pageSize,
          pageNo:this.pagination.pageNo
        })
      }).then(res => {
        if (res.code == 200 ) {
          /**
           * 存导出的数据? 暂时废弃
           */
          // searchParams.token = this.$cookie.get('token')
          // let a = this.tbl + '?'
          // for(let k in searchParams){
          //   a = a+k+'='+ searchParams[k]+ '&'
          // }
          // this.exportParams = a
          //   小区的展示统计量信息数据
          this.pagination.total= this.$com.confirm(res, 'data.totalRows', 0)
          this.pagination.totStCnstArea= this.$com.confirm(res, 'data.totStCnstArea', 0)
          this.pagination.totUnits= this.$com.confirm(res, 'data.totUnits', 0)
          this.pagination.totHous= this.$com.confirm(res, 'data.totHous', 0)

          this.tableData = this.$com.confirm(res, 'data.content', [])
          //  处理显示的字段
          this.tableData.forEach(col=>{
            if (col.stKind == '01') {
              col.stKind = '商品房'
            } else if(col.stKind == '02') {
              col.stKind = '动迁房'
            }else if(col.stKind == '03') {
              col.stKind = '共有产权保障房'
            }else if(col.stKind == '04') {
              col.stKind = '售后房'
            }else if(col.stKind == '05') {
              col.stKind = '直管公房'
            }else if(col.stKind == '06') {
              col.stKind = '混合'
            }else if(col.stKind == '07') {
              col.stKind = '系统公房'
            }else if(col.stKind == '08') {
              col.stKind = '集体土地集资房'
            }else if(col.stKind == '09') {
              col.stKind = '军产'
            }else if(col.stKind == '10') {
              col.stUseType = '私产'
            }else if(col.stKind == '11') {
              col.stUseType = '公租房'
            }
            if (col.sectType == '1') {
              col.sectType = '住宅'
            } else if(col.sectType == '2') {
              col.sectType = '非住宅'
            }else if(col.sectType == '3') {
              col.sectType = '虚拟小区'
            }
            if (col.hocId == '' || col.hocId == null || col.hocId == 0) {
              col.hocId = '否'
            } else {
              col.hocId = '是'
            }
          })
        }
        //
        // 存储当前页面列表的搜索信息
        //
        this.$com.storeSearchParams(
          this.$route.name,
          this.pagination,
          Object.assign({},this.searchForm,{
            'stNameFrst_l': this.form.getFieldValue('stNameFrst_l') || '',
            'addrFrst_l': this.form.getFieldValue('addrFrst_l') || '',
            'c.cspId': this.form.getFieldValue('c.cspId')|| '',
            'c.hoId': this.form.getFieldValue('c.hoId')|| '',
            'c.streetId': this.form.getFieldValue('c.streetId')|| '',
            'stKind_in': this.form.getFieldValue('stKind_in')|| '',
            'isHoc': this.form.getFieldValue('isHoc')|| '',
          },obj)
        )
      })
    },
    getStreet(){      //获取街道下拉
      this.$ajax.get({
        url: this.$api.GET_STREET_LIST,
      }).then(res => {
        this.street = this.$com.confirm(res, 'data.content', [])
      })
    },
    getHos(){   // 获取房办的下拉选项
      this.$ajax.get({
        url: this.$api.GET_HOS_LIST,
        params:{
          pageSize:100000,
          sectType_in:'1'
        }
      }).then(res => {
        this.hos = this.$com.confirm(res, 'data.content', [])
      })
    },
    getWy(){   // 获取物业的下拉选项
      this.$ajax.get({
        url: this.$api.GET_PROPCOMPANIES_LIST,
        params:{
          pageSize:100000,
          sectType_in:'1'
        }
      }).then(res => {
        this.wuye= this.$com.confirm(res, 'data.content', [])
      })
    },
    /**
     * 从vuex中或已存储的搜索条件，判断此条件是否为当前路由的 。如果是则使用
     */
    getSearchParams(){
      let 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 'stNameFrst_l':
              this.form.setFieldsValue({ 'stNameFrst_l': searchParams.params[elem] })
              break
            case 'addrFrst_l':
              this.form.setFieldsValue({ 'addrFrst_l': searchParams.params[elem] })
              break
            case 'c.cspId':
              if (searchParams.params[elem] != '') {
                this.form.setFieldsValue({ 'c.cspId': searchParams.params[elem] })
              }
              break
            case 'c.hoId':
              if (searchParams.params[elem] != '') {
                this.form.setFieldsValue({ 'c.hoId': searchParams.params[elem] })
              }
              break
            case 'stKind_in':
              if (searchParams.params[elem] != '') {
                this.form.setFieldsValue({ 'stKind_in': searchParams.params[elem] })
              }
              break
            case 'c.streetId':
              if (searchParams.params[elem] != '') {
                this.form.setFieldsValue({ 'c.streetId': searchParams.params[elem] })
              }
              break
            case 'isHoc':
              if (searchParams.params[elem] != '') {
                this.form.setFieldsValue({ 'isHoc': searchParams.params[elem] })
              }
              break
            default:
              break
            }
            //   无法回显自定义的值,store里面有数据但是会报 You cannot set a form field before rendering a field associated with the value.
            // setTimeout(()=>{
            //   this.form.setFieldsValue({ elem : searchParams.params[elem] })
            // },0)
          })
        }
        if(!!searchParams.pagination){
          if(!!searchParams.pagination.pageNo){
            this.pagination.pageNo = searchParams.pagination.pageNo
            this.pagination.current = searchParams.pagination.current
            this.pagination.pageSize = searchParams.pagination.pageSize
          }
        }
      }
      this.getList()
    },
    toView(row){      // 操作里面去详情
      this.$router.push({path: `/houseData/basicInfo/${row.id}`,query:{id:row.id,name:row.cspName}})
    },
    toBul(row){
      this.$router.push({path: '/houseData/buildings',query: {id: row.id}})
    },
    toShebei(row){
      this.$router.push({path: `/houseData/shebei/${row.id}`})
    },
    exportList(){              //导出功能
      let formValue = this.form.getFieldsValue()
      let newUrl = this.tbl + '?'
      let newObj  = {}

      //拼接除 c.xxx 和 是否成立业主大会 之外的数据
      for(let k in formValue){
        if (k!= 'isHoc') {                // 排除isHoc  是否成立业主大会   后续判断
          if (formValue[k]!= undefined ) {          // 判断是否值为 undefined
            if ( k == 'c') {                  // 排除 c.xxx 的键
              newObj = formValue[k]               //有c.xx存入 b对象  下面处理,
            } else if(Object.prototype.toString.call(formValue[k])== '[object Array]'){
              // 数组的话就拼接字符串
              newUrl += k +'=' + formValue[k].join(',') + '&'
            }else if (Object.prototype.toString.call(formValue[k]) === '[object Object]') {
              //时间格式对象就转换成字符串
              newUrl += k +'=' +this.$moment(formValue[k]).format('YYYY-MM-DD') +'&'
            }else {
              newUrl += k +'=' +formValue[k] +'&'               //没有特殊情况  直接拼接到 newUrl
            }
          }
        }
      }
      // 处理 c.xxx 里面的数据
      for(let k in newObj ){
        if (newObj[k] != undefined) {                        // 排除值为undefined的键
          newUrl += 'c.'+ k +'=' +newObj[k].split('#')[1] +'&'        // 拼接到 newUrl
        }
      }
      // 处理是否成立业主大会
      if (formValue.isHoc) {
        if (formValue.isHoc=='false') { // 判断业主大会是否选择了,  再根据 选项   拼接参数到 newUrl
          newUrl= newUrl+ 'hocId=null&'
        } else {
          newUrl= newUrl+ 'hocId_ne=null&'
        }
      }
      let token =  this.$cookie.get('token') // 获取token 并拼接到 newUrl
      newUrl +=  'sectType=1&token=' + token 
      window.open (this.$api.BASE_URL+'/service-search/export/'+ newUrl)
    },
  },

}
</script>

<style scoped>
</style>

