<template>
  <criteria-paged :model="model" v-ref:paged>
    <p class="bg-info text-center" style="padding: 8px;font-size: 20px">用户信息</p>
    <criteria partial='criteria' @condition-changed='$parent.search' v-ref:cri>
      <div class="form-horizontal select-overspread container-fluid auto" novalidate partial>
        <div class="row">
          <div class="col-sm-3 form-group">
            <label class="font_normal_body">组织机构</label>
            <res-select restype='organization'
                        @res-select="$parent.$parent.getorg"
                        :initresid='$parent.$parent.curorgid'>
            </res-select>
          </div>
          <div class="col-sm-3 form-group">
            <label class="font_normal_body">账单月份</label>
            <datepicker placeholder='账单月份' style="width:60%"
                        v-model="model.hand_date" :value.sync="model.hand_date"
                        :format="'yyyy-MM'" :show-reset-button="true"
                        condition="hand_date = '{}'">
            </datepicker>
          </div>
          <div class="form-group col-sm-3">
            <label class="font_normal_body">用户编号</label>
            <input  type="text" class="form-control" v-model="model.f_userinfo_code" placeholder='用户编号' v-filter v-figure_filter
                    condition="f_userinfo_code = '{}'" v-next-el='username'  style="width: 60%"
                    :size="model.f_userinfo_code ? model.f_userinfo_id.length  : 4">
          </div>
          <div class="form-group col-sm-3">
            <label class="font_normal_body">用户姓名</label>
            <input  type="text" class="form-control" v-model="model.f_user_name" placeholder='用户姓名'
                    condition="f_user_name = '{}'" v-next-el='area'  style="width: 60%"
                    :size="model.f_user_name ? model.f_user_name.length * 2 : 4">
          </div>
<!--          <div class="form-group col-sm-3">-->
<!--            <label class="font_normal_body">用户类型</label>-->
<!--            <v-select :value.sync="model.f_user_type" v-model="model.f_user_type"-->
<!--                      :options='$parent.$parent.getusertype' placeholder='用户类型'-->
<!--                      close-on-select-->
<!--                      condition="f_user_type = '{}'"-->
<!--                      style="width: 60%">-->

<!--            </v-select>-->
<!--          </div>-->
          <div class="form-group col-sm-3">
            <label class="font_normal_body">用户地址</label>
            <input  type="text" class="form-control" v-model="model.f_address" placeholder='用户地址' v-filter
                    condition="f_address like '%{}%'" v-next-el='cx' v-el:resentialarea style="width: 60%"
                    :size="model.f_address ? model.f_address.length * 2 : 4">
          </div>
          <div class="span" style="float:right;">
            <button class="button_search button_spacing width-60" @click="search()" v-el:cx>查询</button>
            <button class="button_clear button_spacing width-60" @click="$parent.$parent.getcreate()" >生成短信</button>

            <button v-show="$parent.$parent.rollback" class="button_clear button_spacing width-60" @click="$parent.$parent.retrun()"  v-el:cba>返回</button>
            <!-- <export-excel :data="{orderitem: 'f_userinfo_id',condition: condition}" sqlurl="rs/excel/report/getArrearsInfo/欠费记录导出Excel模板"></export-excel> -->
            <div
              :class="{'button_shrink_top':$parent.$parent.criteriaShow,'button_shrink_bottom':!$parent.$parent.criteriaShow}"
              @click="$parent.$parent.hidden()" class="button_spacing" style="float: right">
            </div>
          </div>
        </div>
      </div>
    </criteria>

    <data-grid  :model="model" partial='list' class="table_sy"  v-ref:grid>
      <template partial='head'>
        <tr>
          <th>
            <input type="checkbox"  @click="$parent.$parent.$parent.isAll(model.pageIndex)">
          </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>
          <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">
          <input type="checkbox" v-model="$parent.$parent.$parent.ids"
                 :value="row.f_userinfo_code">
        </td>
        <td>{{$index+1}}</td>
        <td style="text-align:center">{{row.f_user_name}}&nbsp;&nbsp;</td>
        <td style="text-align:center">{{row.f_userinfo_code}}</td>
        <td style="text-align:center">{{row.f_address}}</td>
        <td style="text-align:center">{{row.hand_date}}</td>
        <td style="text-align:center">{{row.f_last_input_date}}</td>
        <td style="text-align:center">{{row.f_input_date}}</td>
        <td style="text-align:center">{{row.f_last_tablebase}}</td>
        <td style="text-align:center">{{row.f_tablebase}}</td>
        <td style="text-align:center">{{row.f_oughtamount}}</td>
        <td style="text-align:center">{{row.f_oughtfee}}</td>
        <td style="text-align:center">{{row.f_stair_gas1}}</td>
        <td style="text-align:center">{{row.f_stair_price1}}</td>
        <td style="text-align:center">{{row.f_stair_gas2}}</td>
        <td style="text-align:center">{{row.f_stair_price2}}</td>
        <td style="text-align:center">{{row.f_stair_gas3}}</td>
        <td style="text-align:center">{{row.f_stair_price3}}</td>
        <td style="text-align:center">{{row.f_balance}}</td>
      </template>
    </data-grid>
  </criteria-paged>
  <user-defined-message :show="definedShow" v-ref:printbill v-on:toggle="close"></user-defined-message>
  <modal v-if="allshow" :show.sync="allshow" v-ref:modal backdrop="false">
    <header slot="modal-header" class="modal-header">
      <h4 class="modal-title">短信发送</h4>
    </header>
    <article slot="modal-body" class="modal-body">
<!--      <div class="form-group row" style="height:auto">-->
<!--        <label class="label-control">短信内容：</label>{{msg}}-->
<!--      </div>-->
      <div class="form-group">
        <label class="label-control">定时发送日期</label>
        <datepicker  placeholder="定时发送日期" :value.sync="sendtimeingdate" :disabled-days-of-Week="[]" :format="'yyyy-MM-dd HH:mm:ss'" :show-reset-button="reset"></datepicker>
      </div>
      <div class="form-group">
        <label class="label-control">发送截至日期</label>
        <datepicker  placeholder="发送截至日期" :value.sync="alldownDate" :disabled-days-of-Week="[]" :format="'yyyy-MM-dd HH:mm:ss'" :show-reset-button="reset"></datepicker>
      </div>
    </article>

    <footer slot="modal-footer" class="modal-footer">
      <button v-show="allshow" type="button" class="btn btn-default width-60" @click='allclose'>取消</button>
      <button v-show="allshow" type="button" class="btn btn-success width-60" @click='create()'>确认</button>
    </footer>
  </modal>
  <modal :show.sync="infoshow" width="1100px" title="短信模板选择" v-ref:modal large backdrop="false">
    <article slot="modal-body" class="modal-body">
      <criteria-paged :model="model2" v-ref:paged2>
        <data-grid :model="$parent.$parent.model2" v-ref:grid2  partial='list'>
          <template partial='head'>
            <tr>
              <!--<th style="padding: 0;border: 0">
                <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"/>
              </th>-->
              <th><nobr>选择</nobr></th>
              <th><nobr>短信类型</nobr></th>
              <th><nobr>模板内容</nobr></th>
              <th><nobr>模板状态</nobr></th>
              <th><nobr><b>创建人</b></nobr></th>
              <th><nobr>操作</nobr></th>
            </tr>
          </template>
          <template partial='body'>
            <td style="text-align: center;"><input type="checkbox" v-model="$parent.$parent.$parent.$parent.sendmodelids" :value="row"></td>
            <td style="text-align: center;">{{row.f_send_type}}</td>
            <td style="text-align: center;" title="{{row.f_user_defined}}" >{{row.f_user_defined}}</td>
            <td style="text-align: center;">{{row.f_state }}</td>
            <td style="text-align: center;"><b>{{row.f_operator}}</b></td>
            <td style="text-align: center;"><nobr>
              <a @click='$parent.$parent.$parent.$parent.edit(row)'>编辑</a>&nbsp;&nbsp;&nbsp;&nbsp;<a @click='$parent.$parent.$parent.$parent.senddelete(row)'>删除</a>
            </nobr></td>
          </template>
        </data-grid>
      </criteria-paged>
    </article>
    <footer slot="modal-footer" class="modal-footer">
      <button type="button" class="btn btn-success width-60" @click='create1'>确定</button>
      <button type="button" class="btn btn-default width-60" @click='infoclose'>关闭</button>
    </footer>
  </modal>
  <modal :show.sync="allshow2" v-ref:modal backdrop="false">
    <header slot="modal-header" class="modal-header">
      <h4 class="modal-title">修正短信内容</h4>
    </header>
    <article slot="modal-body" class="modal-body">
      <div class="form-group row" style="height:auto">
        <label class="label-control">原短信内容：</label>{{msg_old}}
      </div>
      <div class="form-group">
        <label class="label-control">修正为：</label>
        <div class="row auto">
          <textarea class="form-control col-sm-4" v-model="msg_new" rows="8" placeholder=""></textarea>
        </div>
      </div>
      <div class="form-group" style="text-align: center;">
        <h4><b>字数:<span style="color: #5cb85c">{{fontSizeNum}}</span></b></h4>
      </div>
    </article>
    <footer slot="modal-footer" class="modal-footer">
      <button v-show="allshow2" type="button" class="btn btn-default width-60" @click='closeEdit'>取消</button>
      <button v-show="allshow2" type="button" class="btn btn-success width-60" @click='createEdit'>修正</button>
    </footer>
  </modal>
</template>

<script>
/**
 *阶梯水价查询列表
 */
import {HttpResetClass, PagedList} from 'vue-client'
import Vue from 'vue'
import * as Util from '../../../../Util'
import {getLastDayOfMonth} from '../../../../Util'

// let readySomething = async function (self) {
//   // await self.$LoadParams.loadParam(self.f_filialeid)
//   // self.loadMeterBooks()
//   //self.$refs.paged.$refs.cri.model.startDate = self.$login.toStandardDateString() + ' 00:00:00'
//   self.$refs.paged.$refs.cri.model.endDate = self.$login.toStandardDateString() + ' 23:59:59'
// }

export default {
  data () {
    return {
      model: new PagedList('rs/sql/getAccountUser', 50),
      model2: new PagedList('rs/sql/getSendModel', 30, {orderitem: " \'id desc\'"}),
      // 短信模板选择
      infoshow: false,
      startDate: '',
      endDate: '',
      // 下选后其他查询条件
      criteriaShow: false,
      // 短信发送
      definedShow: false,
      allshow: false,
      allshow2: false,
      alldownDate: '',
      sendtimeingdate: '',  // 定时发送日期
      sendtype: '',
      fontSizeNum: 0,
      userdefinedMessage: '',
      meterbrands: [{label: '全部', value: ''}],
      msg: '',
      ids: [],
      pages: [],
      msg_old: '',
      msg_new: '',
      rowEdit: '',
      sendmodelids: [],
      curorgid: [this.$login.f.orgid],
      f_orgid: '',
      f_filialeids: '',
      f_whether: '全部',
      pcdslist: [],
      isFirst: true
    }
  },
  props: {
    orderitem: {
      type: String,
      default: 'f_userinfo_id'
    },
    tablename: {
      type: String,
      default: 't_userinfo'
    },
    items: {
      type: String,
      default: '*'
    },
    rollback: false
  },
  ready () {
    // this.getaddress()
    this.$refs.paged.$refs.cri.model.hand_date = this.$login.toStandardYearMonth()
    // this.$refs.paged.$refs.cri.search()
  },
  watch: {
    'f_whether' (val) {
      if (val[0] === '欠费') {
        this.$dispatch('all', '欠费')
        this.f_whether = '全部'
      }
    },
    'msg_new' (val) {
      this.fontSizeNum = val.length
    }
  },
  methods: {
    getorg (val) {
      this.f_orgid = this.$login.convertToIn(val)
      this.f_filialeids = val[0]
    },
    loadMeterBooks () {
      let meterbrand = this.$GetSaleParam.getGasbrand()
      for (let row of meterbrand) {
        this.meterbrands.push({label: row.label, value: row.value.f_meter_brand})
      }
    },
    retrun () {
      this.alllist = false
      this.$dispatch('allchange4')
    },
    async getaddress () {
      console.log('开始获取小区')
      let HttpReset = new HttpResetClass()
      var data = await HttpReset.load('POST', 'rs/sql/address_getarealist', {
        data: {
          condition: `1=1 and s.f_filialeid = '${this.$login.f.orgid}'`
        }
      }, {resolveMsg: null, rejectMsg: '获取小区失败!'})
      console.log('小区', data.data)
      let house = []
      for (let row of data.data) {
        console.log('开始保存小区')
        house.push({label: row.f_residential_area, value: row.f_residential_area})
      }
      this.residentialArea = house
      this.pcdslist = []
      let req = await HttpReset.load('POST', 'rs/sql/address_singleTableOrderBy?pageNo=1&pageSize=9999999', {
        data: {
          items: '*',
          tablename: 't_pcd',
          orderitem: 'id',
          condition: `1=1 and f_filialeid = '${this.$login.f.orgid}'`
        }
      }, {resolveMsg: null, rejectMsg: '获取地址失败!'})
      let redata = []
      req.data.forEach((row, n) => {
        redata[n] = {
          label: row.f_pcd,
          value: row.id,
          data: row,
          id: row.id
        }
      })
      this.pcdslist = redata
    },
    hidden () {
      this.criteriaShow = !this.criteriaShow
    },
    closeEdit () {
      this.allshow2 = false
    },
    senddelete (row) {
      let setpos = {
        id: row.id,
        f_state: '无效'
      }
      this.$resetpost('rs/entity/t_send_model', setpos, {resolveMsg: '模板删除成功', rejectMsg: '模板删除失败'})
      let condition = "f_state=\'有效\'"
      this.model2.search(condition)
    },
    createEdit () {
      this.allshow2 = false
      let setpos = {
        id: this.rowEdit.id,
        f_user_defined: this.msg_new.replace(/'/g, `''`)
      }
      this.$resetpost('rs/entity/t_send_model', setpos, {resolveMsg: '模板修正成功', rejectMsg: '模板修正失败'})
      this.rowEdit = ''
      this.msg_new = ''
      this.msg_old = ''
      this.sendmodelids = []
      let condition = "f_state=\'有效\' and f_orgid = \'" + Vue.$login.f.orgid + "\'"
      this.model2.search(condition)
    },
    edit (row) {
      this.allshow2 = true
      this.rowEdit = row
      this.msg_old = row.f_user_defined
      this.msg_new = row.f_user_defined
    },
    getsendmodel () {
      let condition = "f_state=\'有效\'"
      let res = this.model2.search(condition)
      console.log('---------------------' + res)
      console.log('this.model2:', this.model2)
      this.infoshow = true
    },
    infoclose () {
      this.infoshow = false
    },
    getcreate () {
      this.allshow = true
    },
    create () {
      if (this.sendtimeingdate && this.sendtimeingdate != '') {
        if (new Date(this.sendtimeingdate).getTime() <= new Date().getTime()) {
          this.$showAlert('定时发送时间不能小于当前时间', 'warning', 2000)
          return
        }
      }
      if (this.alldownDate && this.alldownDate != '') {
        if (new Date(this.alldownDate).getTime() <= new Date().getTime()) {
          this.$showAlert('发送截至日期不能小于当前时间', 'warning', 2000)
          return
        }
      }

      this.allshow = false
      this.model.condition = this.model.condition + " and f_orgid = \'" + Vue.$login.f.orgid + "\'"
      if (this.ids.length !== 0) {
        console.log('ids', this.ids)
        let tems = ''
        for (let i = 0; i < this.ids.length; i++) {
          tems += `'${this.ids[i]}',`
        }
        console.log('tems', tems.substr(0, tems.length - 1), tems)
        this.model.condition = this.model.condition + `and f_userinfo_code in (${tems.substr(0, tems.length - 1)})`
      }
      this.userdefinedMessage = 'selfAccount'
      if (this.userdefinedMessage === '' || this.userdefinedMessage === null || this.alldownDate === '' || this.alldownDate === null) {
        this.$showAlert('短信模板及发送截至时间都不能为空！', 'danger', 3000)
      } else {
        this.$dispatch('create', this.model.condition, this.userdefinedMessage, this.alldownDate, this.sendtype, this.startDate, this.endDate, this.sendtimeingdate)
        this.sendmodelid = []
        this.userdefinedMessage = ''
        this.alldownDate = ''
        this.sendtype = ''
      }
      this.$refs.paged.$refs.cri.search()
    },
    create1 () {
      console.log('kaishi ===', this.sendmodelids)
      if (this.alldownDate === '' || this.alldownDate === null) {
        if (this.sendmodelids.length !== 1) {
          this.$showAlert('短信模板未选择或选择多个！', 'danger', 3000)
        } else {
          console.log('kaishi ===', this.sendmodelids[0])
          this.userdefinedMessage = this.sendmodelids[0].f_user_defined
          this.sendtype = this.sendmodelids[0].f_send_type
          this.sendmodelids = []
          this.msg = this.userdefinedMessage
          this.infoshow = false
          this.allshow = true
        }
      }
    },
    search (args) {
      console.log('args1:', args)
      args.condition = `${args.condition} and f_user_state = '正常'`
      args.condition = `${args.condition} and f_orgid = '${Vue.$login.f.orgid}'`
      console.log(this.$refs.paged.$refs.cri.model.hand_date + '-01')
      this.startDate = this.$refs.paged.$refs.cri.model.hand_date + '-01'
      this.model.params.startDate = this.$refs.paged.$refs.cri.model.hand_date + '-01'
      // 获取开始时间和结束实际
      this.model.params.endDate = Util.getLastDayOfMonth(this.$refs.paged.$refs.cri.model.hand_date + '-01')
      this.endDate = Util.getLastDayOfMonth(this.$refs.paged.$refs.cri.model.hand_date + '-01')
      console.log('args.model', args.model)
      this.model.search(args.condition, args.model)
      if (this.isFirst) {
        this.isFirst = false
      } else {
        this.$dispatch('allchange3')
        this.alllist = true
      }
    },
    addsendmodel () {
      this.definedShow = true
    },
    allclose () {
      this.allshow = false
    },
    close () {
      this.definedShow = false
    },
    isAll (page) {
      if (this.pages.includes(page)) { // 已添加,取消动作
        // 从ids中删除本页所有数据的ids
        this.addOrRemove(false)
        this.pages = this.pages.filter((item) => {
          return item !== page
        })
      } else { // 未添加
        this.pages.push(page) // 添加id，添加动作
        this.addOrRemove(true)
      }
    },
    addOrRemove (is) {
      let that = this
      if (is) { // 添加本页所有数据到ids中
        this.model.rows.forEach((row) => {
          if (!that.ids.includes(row.f_userinfo_code)) {
            that.ids.push(row.f_userinfo_code)
          }
        })
      } else { // 从ids中取消所有的数据
        this.model.rows.forEach((row) => {
          that.ids = that.ids.filter((item) => {
            return item !== row.f_userinfo_code
          })
        })
      }
    }
  },
  events: {
    'definedMessage' (val) {
      this.definedShow = false
    }
  }
}
</script>
<style>
.form-group {
  height: 30px;
}
</style>
