// 物企列表
<template>
  <div class="routerWapper">
    <div v-if="$route.name == 'propertyInfo' && $permission('000103')" class="layoutMargin layoutPadding">
      <a-form :form="form" class="protalForm" >
        <a-row class="formItem" type="flex" align='top' :gutter="18">
          <!-- <a-col span="10">
            <a-form-item label="统一社会信用代码" class="formItem" :label-col="{span:10}" :wrapper-col="{span:14}">
              <a-input placeholder="请输入查询内容" v-decorator="['orgCode_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="['cspName_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 placeholder="请选择排序方式" v-decorator="['managedNum']">
                <a-select-option value="managedNum_asc">正序</a-select-option>
                <a-select-option value="managedNum_desc">倒序</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" v-if="$permission('00010304')">导出数据</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>
      <a-modal width="93%" title="小区列表" v-model="basicInfo" :footer="null">
        <a-table class="portalTable"
          size="small"
          rowKey="id"
          :pagination="paginationModal"
          :columns="columnsModal"
          :dataSource="tableDataModal"
          bordered
          >
          <span slot="action" slot-scope="text, record">
              <span class="actionBtn" @click="toModalView(record)">查看</span>
            </span>
          </a-table>
      </a-modal>
    </div>
    <RouterWapper v-else></RouterWapper>
  </div>
</template>

<script>
export default {
  name: 'propertyInfo',
  data() {
    return {
      basicInfo: false,
      tableData: [], // 总数据
      tableDataModal: [], // 弹框数据
      columnsModal: [ //未开启自定义字段展示的列
        {
          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: 'action',
          width: 160,
          scopedSlots: {
            customRender: 'action'
          }
        }
      ],
      customKeyEnable: false, // cookie里存的是否开启自定义字段
      tbl: 'tbl_prop_company', // 当前表名,
      searchList: [], // 动态渲染的搜索列表
      keyCodeList: [], // 动态搜索的keycode列表
      searchParams: {}, //搜索的列表
      searchForm: {},
      columns: [ //未开启自定义字段展示的列
        {
          title: '物业企业名称',
          dataIndex: 'cspName',
          key: 'cspName'
        },
        {
          title: '组织机构代码',
          dataIndex: 'orgCode',
          key: 'orgCode'
        }, {
          title: '物业企业注册地址',
          dataIndex: 'registerAddress',
          key: 'registerAddress'
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 160,
          scopedSlots: {
            customRender: 'action'
          }
        }
      ],
      pagination: { // 分页信息
        pageNo: 1,
        pageSize: 20,
        showTotal: total => `总条数: ${total}`,
        total: 0,
        current: 1,
        defaultCurrent: 1,
        defaultPageSize: 20,
        showQuickJumper: true,
        onChange: this.pageChange,
        showSizeChanger: true,
        onShowSizeChange: this.showSizeChange,
        pageSizeOptions: ['10', '20', '50', '100'],
      },
      paginationModal: { // 弹框分页信息
        pageNo: 1,
        pageSize: 20,
        total: 0,
        current: 1,
        defaultCurrent: 1,
        defaultPageSize: 20,
        showQuickJumper: true,
        onChange: this.pageChangeModal,
        showSizeChanger: true,
        onShowSizeChange: this.showSizeChangeModal,
        pageSizeOptions: ['10', '20', '50', '100'],
      },
      nowId: '', // 当前小区id
    }
  },
  // compu
  beforeCreate() { // 页面进来创建form
    this.form = this.$form.createForm(this)
  },
  created () { // 进页面获取数据
    this.customKeyEnable=this.$cookie.get('customKeyEnable')
    if(this.customKeyEnable && this.customKeyEnable == 'true'){
      // this.getKeys()
      // this.getAllKeys()
    }else {
      this.getList()
    }
  },
  mounted(){
    if (this.$route.name == 'propertyInfo') {
      this.$nextTick(function () {
        this.form.setFieldsValue({'managedNum': 'managedNum_desc'})
        this.getSearchParams()
      })
    }
    if (this.$route.query.source =='wy') {
      this.$nextTick(function () {
        this.paginationModal.pageNo = this.$route.query.pageNo
        this.paginationModal.current = +this.$route.query.pageNo
        this.paginationModal.pageSize = +this.$route.query.pageSize
        this.basicInfo = true
        this.toList(this.$route.query.cspId)
      })
    }
  },
  methods: {
    handleChangeZdy(i, e){ // 自定义字段 - 搜索条件的 change
      if (Object.prototype.toString.call(e)== '[object Array]') {
        e2 = e.join(',')
      } else if (Object.prototype.toString.call(e)== '[object Object]') {
        e2 = this.$moment(e).format('YYYY-MM-DD')
      }
      this.form.setFieldsValue({ // 传入的i 是i.keyCode   将form表单设置成最新的值
        i: e2
      })
      setTimeout(() => { // 延时器,去掉会拿不到最新的value
        this.getList()
      }, 0)
    },
    backPage(){ // 返回按钮
      this.$router.back()
    },
    getList(){ // 获取数据
      //处理动态的搜索条件,耦合到搜索列表
      const 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)
      })
      const searchParams = Object.assign({}, {
        'cspName_l': !this.form.getFieldValue('cspName_l')? '': this.form.getFieldValue('cspName_l'),
        'sectType_in': '1',
      }, obj)
      if(this.form.getFieldValue('managedNum')){
        searchParams[this.form.getFieldValue('managedNum')] = 1
      }
      this.searchParams = searchParams
      this.$ajax.get({
        url: this.$api.GET_PROPCOMPANIES_LIST,
        params: Object.assign({}, searchParams, {
          pageSize: this.pagination.pageSize,
          pageNo: this.pagination.pageNo,
        })
      }).then(res => {
        if (res.code === '200') {
          /**
           *      在请求数据的成功的时候   保存请求的各项数据及token   后面下载用
           */
          searchParams.token = this.$cookie.get('token')
          let a = this.tbl + '?'
          for(const k in searchParams){
            a = a+k+'='+ searchParams[k]+ '&'
          }
          this.exportParams = a
          // 正常请求数据得到的结果
          this.pagination.total= this.$com.confirm(res, 'data.totalRows', 0)
          this.tableData = this.$com.confirm(res, 'data.content', [])
        }
        //
        // 存储当前页面列表的搜索信息
        //
        this.$com.storeSearchParams(
          this.$route.name,
          this.pagination,
          searchParams
        )
      })
    },
    /**
     * 从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 'cspName_l':
              this.form.setFieldsValue({ 'cspName_l': searchParams.params[elem] })
              break
            // case 'orgCode_l':
            //   this.form.setFieldsValue({ 'orgCode_l': searchParams.params[elem] })
            //   break
            default:
              break
            }
          })
        }
        if(!!searchParams.pagination){
          if(!!searchParams.pagination.pageNo){
            this.pagination.pageNo = searchParams.pagination.pageNo
            this.pagination.current = searchParams.pagination.pageNo
            this.pagination.pageSize = searchParams.pagination.pageSize
          }
        }
      }
      this.getList()
    },
    pageChange(page){ //分页切换
      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()
    },
    toView(params){ // 操作里面去详情
      this.$router.push({path: `/houseData/propertyInfo/${params.id}`, query: {id: params.id, name: params.cspName }})
    },
    toList(params){ // 去小区列表
      // this.$router.push({path: '/houseData/basicInfo',query:{id:params.id,name:params.cspName}})
      this.basicInfo = true
      this.getBasicList(params)
      this.nowId = params
    },
    getBasicList(val){ // 获取弹框数据
      //处理动态的搜索条件,耦合到搜索列表
      const searchParams = Object.assign({}, {
        'c.cspId': val,
        'sectType_in': '1',
      }, {
        'c.createTime_desc': 'desc'
      })
      this.$ajax.get({
        url: this.$api.GET_BASIC_LIST,
        params: Object.assign({}, searchParams, {
          pageSize: this.paginationModal.pageSize,
          pageNo: this.paginationModal.pageNo
        })
      }).then(res => {
        if (res.code == 200 ) {
          // 正常请求数据得到的结果
          this.paginationModal.total=res.data.totalRows
          this.tableDataModal = this.$com.confirm(res, 'data.content', [])
          //  处理现实的字段
          this.tableDataModal.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 = '虚拟小区'
            }
          })
        }
      })
    },
    toModalView(row){ // 去小区的详情页
      this.$router.push({path: `/houseData/basicInfo/${row.id}`, query: {id: row.id, name: row.cspName, source: 'wy', cspId: row.cspId, pageNo: this.paginationModal.pageNo, pageSize: this.paginationModal.pageSize }})
    },
    pageChangeModal(page){ //分页切换 ）
      this.paginationModal.pageNo = page
      this.paginationModal.current = page
      this.getBasicList(this.nowId)
    },
    showSizeChangeModal(current, size) {
      this.paginationModal.pageNo = 1
      this.paginationModal.current = 1
      this.paginationModal.pageSize = size
      this.getBasicList(this.nowId)
    },
    exportList(){ //导出功能
      // let formValue = this.form.getFieldsValue()
      let newUrl = this.tbl + '?'
      let newObj = {}
      // console.log(formValue.managedNum)
      // console.log(this.searchParams)
      const formValue = this.searchParams
      delete formValue.token

      for(const k in formValue){
        if (formValue[k]!= undefined ) { // 判断是否值为 undefined
          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
          }
        }
      }

      let token = this.$cookie.get('token') // 获取token 并拼接到 newUrl
      newUrl += '&access_token=' + token.split('bearer ')[1]
      window.open (this.$api.BASE_URL+'/service-basicdatasync-ddd/export/'+ newUrl)
    },
  },
}
</script>
<style scoped>

</style>

