<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 for="startDate" class="font_normal_body">安装日期</label>
              <datepicker id="startDate" placeholder="开始日期" style="width:60%"
                          v-model="model.startDate"
                          :value.sync="model.startDate"
                          condition="f_install_date >= '{}'"
                          :format="'yyyy-MM-dd HH:mm:ss'"
                          :show-reset-button="true"
              >
              </datepicker>
            </div>
            <div class="col-sm-3 form-group">
              <label for="endDate" class="font_normal_body">&nbsp;&nbsp;&nbsp;&nbsp;至&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>
              <datepicker id="endDate" placeholder="结束日期" style="width:60%"
                          v-model="model.endDate"
                          :value.sync="model.endDate"
                          condition="f_install_date <= '{}'"
                          :format="'yyyy-MM-dd HH:mm:ss'"
                          :show-reset-button="true"
              >
              </datepicker>
            </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()" v-if="$parent.$parent.userdefinedMessage">生成短信</button>
              <button class="button_search button_spacing width-60" @click="$parent.$parent.getsendmodel()">选择模板</button>
              <button class="button_clear button_spacing width-60" @click="$parent.$parent.addsendmodel()">新增模板</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 class="row" v-show="$parent.$parent.criteriaShow">
            <div class="form-group col-sm-3">
              <label class="font_normal_body">用户状态</label>
              <v-select id="f_whether"
                        v-model="$parent.$parent.f_whether"
                        placeholder='用户状态'
                        :value.sync="$parent.$parent.f_whether"
                        :options='$parent.$parent.whether'
                        style="width: 60%"
                        close-on-select >
              </v-select>
            </div>
            <div class="form-group col-sm-3">
              <label class="font_normal_body">用户类型</label>
              <v-select
                v-model="model.f_user_type"
                placeholder='用户类型'
                :value.sync="model.f_user_type"
                :options='$parent.$parent.getusertype'
                condition="f_user_type = '{}'"
                style="width: 60%"
                close-on-select >
              </v-select>
            </div>
            <div class="form-group col-sm-3">
              <label class="font_normal_body">用气性质</label>
              <v-select
                v-model="model.f_gasproperties"
                placeholder='用气性质'
                :value.sync="model.f_gasproperties"
                :options='$parent.$parent.gasproperties'
                condition="f_gasproperties = '{}'"
                style="width: 60%"
                close-on-select >
              </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_userinfo_code" placeholder='用户编号' v-filter v-figure_filter
                      condition="f_userinfo_code = '{}'" v-next-el='yhxm' style="width: 60%"
                      :size="model.f_userinfo_code ? model.f_userinfo_code.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='用户姓名' v-filter v-cn_filter
                      condition="f_user_name = '{}'" v-next-el='resentialarea' v-el:yhxm style="width: 60%"
                      :size="model.f_user_name ? model.f_user_name.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_phone" placeholder='用户电话' v-filter v-cn_filter
                      condition="f_user_phone = '{}'" v-next-el='resentialarea' v-el:yhxm style="width: 60%"
                      :size="model.f_user_phone ? model.f_user_phone.length  : 4">
            </div>
            <div class="form-group col-sm-3">
              <label class="font_normal_body">选择区域</label>
              <v-select
                v-model="model.f_pcd"
                placeholder='选择区域'
                :value.sync="model.f_pcd"
                :options='$parent.$parent.pcdslist'
                condition="f_pcd = '{}'"
                style="width: 60%"
                close-on-select >
              </v-select>
            </div>
            <div class="form-group col-sm-3">
              <label class="font_normal_body">选择小区</label>
              <v-select
                v-model="model.f_residential_area"
                placeholder='选择小区'
                :value.sync="model.f_residential_area"
                :options='$parent.$parent.residentialArea'
                condition="f_residential_area = '{}'"
                style="width: 60%"
                close-on-select >
              </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="form-group col-sm-3" >
              <label class="font_normal_body">气表品牌</label>
              <v-select :value.sync="model.gasbrand" v-model="model.gasbrand" style="width: 60%"
                        :options='$parent.$parent.meterbrands' placeholder='气表品牌' close-on-select
                        v-model='$parent.$parent.gasbrand'
                        condition="f_meter_brand = '{}'"
              ></v-select>
            </div>
            <div class="form-group col-sm-3">
              <label class="font_normal_body">用户余额</label>
              <input  type="number" class="form-control " v-model="model.f_balance" placeholder='用户余额' v-filter v-figure_filter
                      condition="f_balance > {}" style="width: 60%"
                      :size="model.f_balance ? model.f_balance.length  : 4">
            </div>
            <div class="form-group col-sm-3">
              <label class="font_normal_body">&nbsp;&nbsp;&nbsp;&nbsp;至&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>
              <input  type="number" class="form-control " v-model="model.f_balance_cur" placeholder='用户余额' v-filter v-figure_filter
                      condition="f_balance <= {}"  style="width: 60%"
                      :size="model.f_balance_cur ? model.f_balance_cur.length  : 4">
            </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>序号</th>
            <th>用户编号</th>
            <th>用户姓名</th>
            <th>用户电话</th>
            <!--<th><nobr>用户区域</nobr></th>-->
            <th>用户地址</th>
            <th>用户余额</th>
            <th>累购气量</th>
            <th>累购金额</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_userinfo_code}}</td>
          <td style="text-align:center">{{row.f_user_name}}</td>
          <td style="text-align:center">{{row.f_user_phone}}</td>
          <!--<td style="text-align:center"><nobr>{{row.f_area}}</nobr></td>-->
          <td style="text-align:center">{{row.f_address}}</td>
          <td style="text-align:center">{{row.f_balance}}</td>
          <td style="text-align:center">{{row.f_total_gas}}</td>
          <td style="text-align:center">{{row.f_total_fee}}</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'

  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/smsUserInfo', 50, {startDate: 'this.model.startDate', endDate: 'this.model.endDate'}),
        model2: new PagedList('rs/sql/getSendModel', 30, {orderitem: " \'id desc\'"}),
        // 短信模板选择
        infoshow: false,
        // 下选后其他查询条件
        criteriaShow: false,
        // 短信发送
        definedShow: false,
        allshow: false,
        allshow2: false,
        alldownDate: '',
        sendtimeingdate: '',  // 定时发送日期
        startDate: '',
        endDate: '',
        sendtype: '',
        fontSizeNum: 0,
        userdefinedMessage: '',
        meterbrands: [{label: '全部', value: ''}],
        msg: '',
        ids: [],
        pages: [],
        msg_old: '',
        msg_new: '',
        rowEdit: '',
        sendmodelids: [],
        // 小区
        residentialArea: [],
        whether: [{ label: '欠费', value: '欠费' },
          { label: '全部', value: '全部' }],
        getusertype: [{ label: '全部', value: '' },

          { label: '民用', value: '民用' },
          { label: '非民用', value: '非民用' }],
        gasproperties: this.$appdata.getParam('用气性质') ? [{
          label: '全部',
          value: ''
        }, ...this.$appdata.getParam('用气性质')] : [],
        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()
      readySomething(this)
      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: {
      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.startDate = this.$refs.paged.$refs.cri.model.startDate
        this.endDate = this.$refs.paged.$refs.cri.model.endDate
        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)})`
        }
        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('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>
