<template>
  <div>
    <criteria-paged :model="model" v-ref:paged>
      <criteria partial='criteria' @condition-changed='search' v-ref:cri>
        <div novalidate class="form-horizontal select-overspread container-fluid auto" partial>
          <div class="col-sm-4 form-group form-input-group" style="width: 20%">
            <label class="control-label">小&nbsp;&nbsp;&nbsp;&nbsp;区</label>
            <input type="text" class="form-control" placeholder="小区" v-model="model.f_residential_area"
                   style="height:34px;margin-top: 8px"   condition="f_residential_area like '%{}%'">
          </div>

          <!--<div class="col-sm-4 form-group form-input-group" style="width: 20%">-->
            <!--<label class="control-label">开始时间</label>-->
            <!--<datepicker-->
              <!--:value.sync="model.f_check_start"-->
              <!--placeholder='开始时间'-->
              <!--:disabled-days-of-week="[]" style="margin-top: 8px"-->
              <!--:format="'yyyy-MM-dd'"-->
              <!--:show-rest-button="reset"-->
              <!--v-model = "model.f_check_start"-->
              <!--condition="f_time > ='{} 00:00:00'">-->
            <!--</datepicker>-->
          <!--</div>-->
          <!--<div class="col-sm-4 form-group form-input-group" style="width: 20%">-->
            <!--<label class="control-label">结束时间</label>-->
            <!--<datepicker-->
              <!--:value.sync="model.f_check_end"-->
              <!--placeholder='结束时间'-->
              <!--:disabled-days-of-week="[]"-->
              <!--:format="'yyyy-MM-dd'" style="margin-top: 8px"-->
              <!--:show-rest-button="reset"-->
              <!--v-model = "model.f_check_end"-->
              <!--condition="f_time <=  '{} 23:59:59'">-->
            <!--</datepicker>-->
          <!--</div>-->
          <div class="col-sm-4 form-group form-input-group" style="width: 20%">
            <label class="control-label">提&nbsp;交&nbsp;人</label>
            <input type="text" class="form-control" placeholder="提交人" v-model="model.f_creater" v-on:keyup.enter="search"
                   style="height:34px;margin-top: 8px"   condition="f_creater like '%{}%'">
          </div>
          <div class="col-sm-4 form-group form-input-group" style="width: 20%">
            <label class="control-label">生成状态</label>
            <v-select id="f_approved"
                      placeholder='审核状态' style="margin-top: 8px"
                      v-model='model.f_is_efficient'
                      :value.sync="model.f_is_efficient"
                      :options='$parent.$parent.f_approval_states'
                      condition="f_is_efficient='{}'"
                      close-on-select clear-button></v-select>
          </div>
          <div class="col-sm-4 form-group form-input-group" style="width: 20%;margin-top:8px;float: right">
            <button class="button_search button_spacing" @click="search()">查询</button>
            <button class="button_new button_spacing" @click="$parent.$parent.verify()">审核通过</button>
            <button class="button_export button_spacing" @click="$parent.$parent.undoall()">审核不通过</button>
          </div>
        </div>
      </criteria>
      <data-grid :model="model" partial='list' v-ref:grid class="table_sy">
        <template partial='head'>
          <tr>
            <th><nobr>
              <input type="checkbox" id="f_operator" v-model="$parent.$parent.$parent.all[model.pageIndex-1]"
                     @change="$parent.$parent.$parent.select()" style="width: 22px;height: 22px"/>
            </nobr></th>
            <th><nobr>用户编号</nobr></th>
            <th><nobr>用户名称</nobr></th>
            <th><nobr>提交人</nobr></th>
            <th><nobr>提交时间</nobr></th>
            <th><nobr>修改类型</nobr></th>
            <th><nobr>审核状态</nobr></th>
            <th><nobr>审核结果</nobr></th>
            <th><nobr>审核人</nobr></th>
            <th><nobr>审核时间</nobr></th>
            <th><nobr>审核</nobr></th>
          </tr>
        </template>
        <template partial='body'>
          <td style="text-align: center"><nobr><input type='checkbox'  v-if="row.f_approved == '未审核'" @change="$parent.$parent.$parent.selectOne($event,row,$index)"
                                                      :checked="$parent.$parent.$parent.ischecked(model.pageIndex-1,$index)" style="width: 22px;height: 22px;"/></nobr></td>
          <td style="text-align: center"><nobr>{{row.f_userinfo_code}}</nobr></td>
          <td style="text-align: center"><nobr>{{row.f_user_name}}</nobr></td>
          <td style="text-align: center"><nobr>{{row.f_modifier}}</nobr></td>
          <td style="text-align: center"><nobr>{{row.f_time}}</nobr></td>
          <td style="text-align: center"><nobr>{{row.f_modify_type}}</nobr></td>
          <td style="text-align: center"><nobr>{{row.f_approved}}</nobr></td>
          <td style="text-align: center"><nobr>{{row.f_approved_result}}</nobr></td>
          <td style="text-align: center"><nobr>{{row.f_approved_by}}</nobr></td>
          <td style="text-align: center"><nobr>{{row.f_approved_time}}</nobr></td>
          <td style="text-align: center"><nobr>
            <button class="button_search button_spacing" @click="$parent.$parent.$parent.change(row)" v-if="row.f_approved == '未审核'">审核</button>
            <button class="button_new button_spacing" @click="$parent.$parent.$parent.change(row)" v-if="row.f_approved != '未审核'">查看</button>
          </nobr></td>
        </template>
      </data-grid>
    </criteria-paged>
    <info-modify-modal v-show="showModal" :info.sync="info" ></info-modify-modal>
  </div>
</template>

<script>
  import { PagedList,HttpResetClass } from 'vue-client'
  import * as Util from '../Util'
  import Vue from 'vue'
  import InfoModifyModal from "./InfoModifyModal";

  export default {
    components: {InfoModifyModal},
    title: '档案审核',
    data() {
      let model = new PagedList('rs/sql/用户档案审核查询', 20, {
        groupitem: '""', orderitem: '"f_time desc"', f_approved: 'this.f_approved[0]',filialestr:'this.filialestr'
      })
      model.filialestr = this.$login.f.f_orgids
      model.f_archive_date = ''
      model.f_approved = ['']
      return {
        showModal: false,
        model: model,
        info: {},
        userinfo:{},
        context: {
          f_user_equipmen:[]
        },
        f_approval_states:[
          {lable:'请选择',value:''},
          {lable:'已生成',value:'已生成'},
          {lable:'未生成',value:'未生成'}
        ],
        rowsdata: [],
        rowsdata1: [],
        //控制全选
        all: [],
        //控制单选
        radio: [],
        equipmensChart: {
          '单灶': '灶具',
          '灶具': '灶具',
          '单热水器': '热水器',
          '热水器': '热水器',
          '单壁挂炉': '壁挂锅炉',
          '壁挂炉': '壁挂锅炉',
          '壁挂锅炉': '壁挂锅炉',
          '表后管': '表后管',
          '灶具连接管': '灶具连接管',
          '报警器': '报警器',
          '立管': '立管',
          '阀门': '阀门',
          '其他': '其他',
          '抽油机': '抽油机',
          '燃气表': '燃气表',
          '燃气取暖器': '',
          '未用': ''
        },
      }
    },
    ready () {
      this.arrAddFun()
      this.search()
    },
    methods: {
      search(){
        let condition = `1=1`
        this.model.search(condition)
      },
      change(row) {
        this.showModal = true
        this.$set('info', row)
      },
      todo(row){
        let r = confirm("确认修改该资料？")
        this.context.f_user_equipmen = []
        if(r) {
          let _http = new HttpResetClass()
           _http.load('POST','rs/sql/查询用户原信息', {data: {id: this.info.f_userinfoid}},{resolveMsg: null, rejectMsg: null}).then((res) => {
            console.log('res==>',res)
            this.userinfo = res.data[0]
            this.$resetpost('rs/sql/getUserDevices', {data: {f_userinfo_id: this.info.f_userinfoid}}).then((ret)=>{
              let f_user_equipmen = ''
              if(ret.data.length > 0){
                for (let i= 0;i< ret.data.length;i++){
                  f_user_equipmen += `${ret.data[i].f_devices_type}+`
                }
                row.f_user_equipmen = f_user_equipmen.slice(0,f_user_equipmen.length-1)
                console.log('row.f_user_equipmen',row.f_user_equipmen)
              }
              row.f_approved = '已审核'
              row.f_approved_result = ''
              row.f_approved_by = this.$login.f.name
              row.f_approved_time = Util.toStandardTimeString()
              let content = JSON.parse(row.f_content)
              console.log('content===>',content)
              let self = this
              if (row.f_modify_type == '用户档案') {
                this.context.f_userinfo_id = row.f_userinfoid
                this.context.f_user_name = this.isnull(content.f_user_name)
                this.context.f_userinfoid = row.f_userinfoid
                this.context.f_meter_style = this.isnull(content.f_meter_style)
                this.context.f_size_card = this.isnull(content.f_size_card)
                this.context.version = row.version
                this.context.f_meternumber = this.isnull(content.f_meternumber)
                this.context.f_residential_area = this.isnull(content.f_residential_area)
                this.context.f_aroundmeter = this.isnull(content.f_flow_direction)
                //将用气设备拆成单个
                if(this.isnull(content.f_user_equipmen).indexOf('+') == -1){
                  console.log('单个设备')
                  if(this.isnull(content.f_user_equipmen) != ''){
                    this.context.f_user_equipmen.push(this.equipmensChart[content.f_user_equipmen])
                  }
                }else{
                  console.log('多个设备')
                  this.context.f_user_equipmen = this.isnull(content.f_user_equipmen).split('+').map(value => this.equipmensChart[value]).filter(value => value !== '')
                }
                // this.context.f_user_equipmen = this.isnull(content.f_user_equipmen)
                this.context.f_heating_style = this.isnull(content.f_heating_style)
                this.context.f_residential_properties = this.isnull(content.f_residential_properties)
                this.context.f_user_phone = this.isnull(content.f_user_phone)
                this.context.f_street = this.isnull(content.f_street)
                this.context.f_area = this.isnull(content.f_area)
                this.context.f_unit = this.isnull(content.f_unit)
                this.context.f_building = this.isnull(content.f_building)
                this.context.f_floor = this.isnull(content.f_floor)
                this.context.f_room = this.isnull(content.f_room)
                this.context.f_address = this.isnull(content.f_address)
                this.context.f_idnumber = this.isnull(content.f_idnumber)
                // this.context.f_userproperties = this.isnull(content.f_userproperties)
                this.context.f_people_num = this.isnull(content.f_people_num)
                // this.context.f_safeagreement_id = this.isnull(content.f_safeagreement_id)
                this.context.f_distinct = this.isnull(content.f_distinct)
                // this.context.f_contract_id = this.isnull(content.f_contract_id)
                this.context.f_comments = this.isnull(content.f_comments)
                row.f_residential_area = this.userinfo.f_residential_area
                row.f_user_name = this.userinfo.f_user_name
                row.f_meternumber = this.userinfo.f_meternumber
                row.f_aroundmeter = this.userinfo.f_flow_direction
                row.f_heating_style = this.userinfo.f_heating_style
                row.f_residential_properties = this.userinfo.f_residential_properties
                row.f_size_card = this.userinfo.f_size_card
                row.f_meter_style = this.userinfo.f_meter_style
                row.f_user_phone = this.userinfo.f_user_phone
                row.f_idnumber = this.userinfo.f_idnumber
                row.area = this.userinfo.f_area
                row.f_street = this.userinfo.f_street
                row.f_unit = this.userinfo.f_unit
                row.f_building = this.userinfo.f_building
                row.f_floor = this.userinfo.f_floor
                row.f_room = this.userinfo.f_room
                row.f_address = this.userinfo.f_address
                row.f_people_num = this.userinfo.f_people_num
                // row.f_safeagreement_id = this.userinfo.f_safeagreement_id
                row.f_distinct = this.userinfo.f_distinct
                // row.f_contract_id = this.userinfo.f_contract_id
                // row.f_userproperties = this.userinfo.f_userproperties
                row.f_comments = this.userinfo.f_comments
                row.f_create_time = Util.toStandardTimeString()
                this.$resetpost('rs/logic/UpdateUserInfo', {data: {row: this.context}}).then((res) => {
                  console.log('保存的row',row)
                  console.log('保存的res',res)
                  if(res.data.code == 200){
                    row.f_approved_result = '通过'
                  }else{
                    if (res.data.areaCode == 500 ){
                      row.f_approved_result = '地址信息未通过'
                    }
                  }
                  self.$resetpost('rs/entity/t_modify_userinfo', row).then((res) => {
                    window.alert('用户信息已保存')
                    this.info = {}
                    this.userinfo = {}
                  })
                }).
                catch(
                  (res) => {
                    window.alert('信息保存失败')
                  })
              }

              if (row.f_modify_type == '表档案') {
                this.context.version = row.version
                this.context.id = content.id
                this.context.f_gaswatchbrand = content.f_maker
                this.context.f_metertype = content.f_diaphgram_size
                this.context.f_gasmeterstyle = content.f_meter_type
                this.context.lastinputgasnum = content.f_prior_reading
                this.context.f_meternumber = content.f_meter_no
                this.context.f_aroundmeter = content.f_flow_direction
                this.$resetpost('rs/logic/SaveEntity', {data: {row: this.context, tablename: 't_userinfo'}}).then((res) => {
                  self.$resetpost('rs/entity/t_modify_userinfo', row).then((res) => {
                    window.alert('用户信息已保存')
                    this.reload()
                  })
                }).catch(
                  (res) => {
                    window.alert('信息保存失败')
                  })
              }
            })
          })
          this.showModal = false
        }
      },
      async verify(){
        this.mergeRowData(this.rowsdata)
        let a =0
        for (let row of this.rowsdata1){
          if (row.f_approved === '未审核'){
            a=a+1
          }
        }
        console.log('a:',a)
        if (a===0){
          this.$showMessage('请至少选择一项')
          return
        }
        if (this.rowsdata1.length===0){
          this.$showMessage('请至少选择一项')
          return
        }
        let data={
          content:[],
          rows:[],
          contentother:[]
        }
        for (let row of this.rowsdata1){
          if (row.f_approved != '未审核'){
            console.log('本条数据已审核')
            continue
          }
            let _http = new HttpResetClass()
            let res= await _http.load('POST','rs/sql/查询用户原信息', {data: {id: row.f_userinfoid}},{resolveMsg: null, rejectMsg: null})
            let ret= await _http.load('POST','rs/sql/getUserDevices', {data: {f_userinfo_id: row.f_userinfoid}},{resolveMsg: null, rejectMsg: null})
            let f_user_equipmen = ''
            if(ret.data.length > 0){
              for (let i= 0;i< ret.data.length;i++){
                f_user_equipmen += `${ret.data[i].f_devices_type}+`
              }
              row.f_user_equipmen = f_user_equipmen.slice(0,f_user_equipmen.length-1)
              console.log('row.f_user_equipmen',row.f_user_equipmen)
            }
              console.log('res==>',res)
              let userinfo = res.data[0]
              row.f_approved = '已审核'
              row.f_approved_result = ''
              row.f_approved_by = this.$login.f.name
              row.f_approved_time = Util.toStandardTimeString()
              let content = JSON.parse(row.f_content)
              console.log('content===>',content)
              let context ={
                f_user_equipmen:[]
              }
              if (row.f_modify_type == '用户档案') {
                context.f_userinfo_id = row.f_userinfoid
                context.id = row.id
                context.f_user_name = this.isnull(content.f_user_name)
                context.f_userinfoid = row.f_userinfoid
                context.f_meter_style = this.isnull(content.f_meter_style)
                context.f_size_card = this.isnull(content.f_size_card)
                context.f_idnumber = this.isnull(content.f_idnumber)
                context.version = row.version
                context.f_residential_area = this.isnull(content.f_residential_area)
                context.f_user_phone = this.isnull(content.f_user_phone)
                context.f_street = this.isnull(content.f_street)
                context.f_area = this.isnull(content.f_area)
                context.f_unit = this.isnull(content.f_unit)
                context.f_building = this.isnull(content.f_building)
                context.f_floor = this.isnull(content.f_floor)
                context.f_room = this.isnull(content.f_room)
                context.f_address = this.isnull(content.f_address)
                // context.f_userproperties = this.isnull(content.f_userproperties)
                if(this.isnull(content.f_user_equipmen).indexOf('+') == -1){
                  console.log('单个设备')
                  if(this.isnull(content.f_user_equipmen) != ''){
                    context.f_user_equipmen.push(this.equipmensChart[content.f_user_equipmen])
                  }
                }else{
                  console.log('多个设备')
                  context.f_user_equipmen = this.isnull(content.f_user_equipmen).split('+').map(value => this.equipmensChart[value]).filter(value => value !== '')
                }
                context.f_heating_style = this.isnull(content.f_heating_style)
                context.f_residential_properties = this.isnull(content.f_residential_properties)
                context.f_comments = this.isnull(content.f_comments)
                context.f_people_num = this.isnull(content.f_people_num)
                // context.f_safeagreement_id = this.isnull(content.f_safeagreement_id)
                context.f_distinct = this.isnull(content.f_distinct)
                // context.f_contract_id = this.isnull(content.f_contract_id)
                context.f_meternumber = this.isnull(content.f_meternumber)
                context.f_residential_area = this.isnull(content.f_residential_area)
                context.f_aroundmeter = this.isnull(content.f_flow_direction)
                row.f_residential_area = userinfo.f_residential_area
                row.f_user_name = userinfo.f_user_name
                row.f_meternumber = userinfo.f_meternumber
                row.f_idnumber = userinfo.f_idnumber
                row.f_aroundmeter = userinfo.f_flow_direction
                //TOdo 字段未确定
                row.f_heating_style = this.userinfo.f_heating_style
                row.f_residential_properties = this.userinfo.f_residential_properties
                row.f_user_phone = userinfo.f_user_phone
                row.area = userinfo.f_area
                row.f_street = userinfo.f_street
                row.f_unit = userinfo.f_unit
                row.f_building = userinfo.f_building
                row.f_floor = userinfo.f_floor
                row.f_room = userinfo.f_room
                row.f_address = userinfo.f_address
                // row.f_userproperties = userinfo.f_userproperties
                row.f_people_num = userinfo.f_people_num
                row.f_meter_style = userinfo.f_meter_style
                row.f_size_card = userinfo.f_size_card
                // row.f_safeagreement_id = userinfo.f_safeagreement_id
                row.f_distinct = userinfo.f_distinct
                // row.f_contract_id = userinfo.f_contract_id
                row.f_comments = userinfo.f_comments
                data.content.push(context)
                data.rows.push(row)
              }
              if (row.f_modify_type == '表档案') {
                context.version = row.version
                context.id = content.id
                context.f_gaswatchbrand = content.f_maker
                context.f_metertype = content.f_diaphgram_size
                context.f_gasmeterstyle = content.f_meter_type
                context.lastinputgasnum = content.f_prior_reading
                context.f_meternumber = content.f_meter_no
                context.f_aroundmeter = content.f_flow_direction
                data.contentother.push(context)
              }

        }
        console.log('数据处理之后',data)
        this.$resetpost('rs/logic/UpdateUserall', {data: {rows: data.content,backData:data.rows}}).then((res) => {
            window.alert('用户信息已保存')
            this.selectInit()
            this.search()
        }).
        catch(
                (res) => {
                  window.alert('信息保存失败')
                  this.selectInit()
                })

        // if (data.contentother.length>0){
        //   this.$resetpost('rs/logic/SaveEntity', {data: {row: data.contentother, tablename: 't_userinfo'}}).then((res) => {
        //     this.selectInit()
        //     this.search()
        //   }).catch(
        //           (res) => {
        //             window.alert('信息保存失败')
        //             this.selectInit()
        //
        //           })
        // }
      },
      isnull(val){
        if(val == null){
          return ''
        }else{
          return val
        }
      },
      undo(row){
        let _http = new HttpResetClass()
        _http.load('POST','rs/sql/查询用户原信息', {data: {id: this.info.f_userinfoid}},{resolveMsg: null, rejectMsg: null}).then((res) => {
          this.userinfo = res.data[0]
          let r = confirm("确认修改内容不通过？")
          if(r) {
            console.log(this.$login.user)
            console.log(this.$login.f)
            row.f_approved = '已审核'
            row.f_approved_result = '未通过'
            row.f_approved_by = this.$login.f.name
            row.f_approved_time = Util.toStandardTimeString()
            this.$resetpost('rs/entity/t_modify_userinfo', row)
            this.showModal = false
            this.userinfo = {}
          }
        })

      },
      async undoall(){
        this.mergeRowData(this.rowsdata)
        let a =0
        for (let row of this.rowsdata1){
          if (row.f_approved === '未审核'){
            a=a+1
          }
        }
        console.log('a:',a)
        if (a===0){
          this.$showMessage('请至少选择一项')
          return
        }
        if (this.rowsdata1.length===0){
          this.$showMessage('请至少选择一项')
          return
        }
        let data={
          rows :[]
        }
        for (let row of this.rowsdata1){
          if (row.f_approved != '未审核'){
            console.log('本条数据已审核')
            continue
          }
          let _http = new HttpResetClass()
         let res= await  _http.load('POST','rs/sql/查询用户原信息', {data: {id: row.f_userinfoid}},{resolveMsg: null, rejectMsg: null})
            this.userinfo = res.data[0]

              console.log(this.$login.user)
              console.log(this.$login.f)
              row.f_approved = '未通过'
              row.f_approved_by = this.$login.f.name
              row.f_approved_time = Util.toStandardTimeString()
              data.rows.push(row)
              this.userinfo = {}


        }
        this.$resetpost('rs/logic/undouserinfo', data)
        this.selectInit()
        this.search()

      },
      arrAddFun() {
        //拓展数组去空值的方法
        Array.prototype.removeEmpty=function () {
          for(var i=0;i<this.length;i++){
            if(this[i]=="" || typeof(this[i])=="undefined"){
              this.splice(i,1);
              i--;
            }
          }
          return this;
        }
      },
      mergeRowData(joinrows){
        let data = []
        //合并
        for(let array of joinrows){

            data.push.apply(data,array);


        }
        //去空
        data = data.removeEmpty()
        console.log('去空前：',this.rowsdata)
        this.rowsdata1 = data
        console.log('去空后：',this.rowsdata1)
      },
      //多选框初始化
      selectInit(){
        this.rowsdata = []
        this.all = []
        this.radio = []

      },
      select(){
        let index = this.model.pageIndex-1
        console.log("全选",this.all[index])
        if(!this.radio[index]){
          this.radio.$set(index,[])
        }
        if(this.all[index]){
          //数据
          this.rowsdata[index] = Object.assign([],this.model.rows)
          //勾选
          for(var i=0;i<this.model.rows.length;i++){
            this.radio[index].$set(i,true)
          }
        }else{
          //数据
          this.rowsdata[index] = []
          //不勾选
          for(var i=0;i<this.model.rows.length;i++){
            this.radio[index].$set(i,false)
          }
        }

      },
      selectOne(event,row,i){
        console.log("单选",event.target.checked)
        let index = this.model.pageIndex-1
        if(!this.rowsdata[index]){
          this.rowsdata[index] = []
        }
        if(!this.radio[index]){
          this.radio.$set(index,[])
        }
        if(event.target.checked){
          //数据
          this.rowsdata[index][i] = row
          //勾选
          this.radio[index].$set(i,true)
          //判断是否全部选中
          var allState = true
          if (this.model.rows.length != this.radio[index].length){
            allState = false
          }
          for(var state of this.radio[index]){
            if(!state){
              allState = false
            }
          }
          if(allState){
            this.all.$set(index,true)
          }else{
            this.all.$set(index,false)
          }
        }else{
          //数据
          this.rowsdata[index][i] = []
          //不勾选
          this.radio[index].$set(i,false)
          //任意取消一个则全选状态设为false
          this.all.$set(index,false)
        }

      }
    },
    computed :{
      ischecked(){
        return function (index,i) {
          // console.log("计算属性")
          if(!this.radio[index]){
            return false
          }
          return this.radio[index][i]
        }
      },
    }
  }
</script>
