<template>
  <div class="flex">
    <work-busy :is-busy="busy"></work-busy>
    <criteria-paged :model="model" v-ref:paged>
      <criteria partial='criteria' @condition-changed='$parent.search' v-ref:criteria>
        <div novalidate class="form-horizontal select-overspread container-fluid auto" partial>
          <div class="row" v-show="!$parent.$parent.$parent.showItemAll">
            <div :class="$parent.$parent.style2" style="margin: 0px">
              <role-selector-safe
                role-name="网格员"
                role-lable="网&nbsp;格&nbsp;员&nbsp;"
                @re-res="$parent.$parent.getRes"
                :value.sync="model.f_checker_id"
                v-model="model.f_checker_id"
                condition=" f_checker_name like '%{}%'">
              </role-selector-safe>
            </div>
            <div :class="$parent.$parent.style">
              <label class="font_normal_body">片区名称</label>
              <v-select :value.sync="model.f_check_book_id" v-model='model.f_check_book_id'
                        :value-single="true" style="width: 60%"
                        class="select_list select"
                        :options='$parent.$parent.checkBooks' placeholder='片区名称'
                        close-on-select
                        condition="tcb.id ='{}'"></v-select>
            </div>

            <div class="form-group col-sm-2">
              <label class="font_normal_body">小&emsp;&emsp;区</label>
              <input type="text" class="input_search" v-model="model.f_residential_area"
                     style="width: 60%" placeholder="小区" condition="f_residential_area like '%{}%'">
            </div>
            <div class="form-group col-sm-2">
              <label class="font_normal_body">街&emsp;&emsp;道</label>
              <input type="text" class="input_search" v-model="model.f_street"
                     style="width: 60%" placeholder="街道" condition="f_street like '%{}%'">
            </div>
            <div class="form-group col-sm-2">
              <label class="font_normal_body">区&emsp;&emsp;县</label>
              <input type="text" class="input_search" v-model="model.f_slice_area"
                     style="width: 60%" placeholder="区县" condition="f_slice_area like '%{}%'">
            </div>
<!--            <div :class="$parent.$parent.style">-->
<!--              <label class="font_normal_body">表册类型</label>-->
<!--              <v-select :value.sync="model.f_check_book_type" v-model='model.f_check_book_type'-->
<!--                        :value-single="true" style="width: 60%"-->
<!--                        class="select_list select"-->
<!--                        :options='$parent.$parent.bookTypes' placeholder='表册类型'-->
<!--                        close-on-select-->
<!--                        condition="tcb.f_check_book_type ='{}'"></v-select>-->
<!--            </div>-->
<!--            <div :class="$parent.$parent.style">-->
<!--              <label class="font_normal_body">用户类型</label>-->
<!--              <v-select :value.sync="model.f_user_type" v-model='model.f_user_type'-->
<!--                        :value-single="true" style="width: 60%"-->
<!--                        class="select_list select"-->
<!--                        :options='$parent.$parent.userTypes' placeholder='用户类型'-->
<!--                        close-on-select-->
<!--                        condition="tcb.f_user_type ='{}'"></v-select>-->
<!--            </div>-->
            <div :class="$parent.$parent.style" style="width: auto;margin-top:8px;float: right">
              <button type="button" class="button_search button_spacing" @click="search()">查询</button>
              <button type="button" class="button_new button_spacing" @click="$parent.$parent.add()">新增片区</button>
              <button type="button" class="button_new button_spacing" @click="$parent.$parent.showModal = true">片区用户管理</button>
              <button type="button" class="button_new button_spacing" @click="$parent.$parent.showModal2 = true">批量修改网格员</button>
              <div style="float: right" class="button_spacing"
                   v-show="$parent.$parent.$parent.showItem ||$parent.$parent.$parent.showItemUser"
                   :class="{'button_shrink_left':$parent.$parent.$parent.showItemAll,'button_shrink_right':!$parent.$parent.$parent.showItemAll}"
                   @click="($parent.$parent.$parent.showItem =false) || ($parent.$parent.$parent.showItemUser =false)"></div>
              </div>


          </div>


          <div class="row" v-show="$parent.$parent.$parent.showItemAll">
            <div :class="$parent.$parent.style2" style="margin: 0px">
              <role-selector-safe
                role-name="网格员"
                role-lable="网&nbsp;格&nbsp;员&nbsp;"
                @re-res="$parent.$parent.getRes"
                :value.sync="model.f_checker_id"
                v-model="model.f_checker_id"
                condition=" f_checker_name like '%{}%'">
              </role-selector-safe>
            </div>
            <div :class="$parent.$parent.style">
              <label class="font_normal_body">片区名</label>
              <v-select :value.sync="model.f_check_book_id" v-model='model.f_check_book_id'
                        :value-single="true" style="width: 60%"
                        class="select_list select"
                        :options='$parent.$parent.checkBooks' placeholder='片区名称'
                        close-on-select
                        condition="tcb.id ='{}'"></v-select>
            </div>
            <div :class="$parent.$parent.style" style="width: auto;margin-top:8px;float: right">
              <button type="button" class="button_search button_spacing" @click="search()">查询</button>
              <button type="button" class="button_new button_spacing" @click="$parent.$parent.add()">新增片区</button>
              <button type="button" class="button_new button_spacing" @click="$parent.$parent.showModal = true">片区用户管理</button>
              <button type="button" class="button_new button_spacing" @click="$parent.$parent.showModal2 = true">批量修改网格员</button>
              <div style="float: right" class="button_spacing"
                   v-show="$parent.$parent.$parent.showItem ||$parent.$parent.$parent.showItemUser"
                   :class="{'button_shrink_left':$parent.$parent.$parent.showItemAll,'button_shrink_right':!$parent.$parent.$parent.showItemAll}"
                   @click="($parent.$parent.$parent.showItem =false) || ($parent.$parent.$parent.showItemUser =false)"></div>
<!--              <div style="float: right" class="button_spacing"-->
<!--                   :class="{'button_shrink_top':$parent.$parent.criteriaShow,'button_shrink_bottom':!$parent.$parent.criteriaShow}"-->
<!--                   @click="$parent.$parent.hidden()">-->
<!--              </div>-->
            </div>

          </div>

        </div>
      </criteria>
      <data-grid :model="model" partial="list" class="list_area table_sy" v-ref:grid>
        <template partial='head'>
          <tr>
            <th><nobr><input type="checkbox" v-model="$parent.$parent.$parent.checkAll"/> 全选</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 v-show="$parent.$parent.$parent.showCaoZuo">-->
<!--              <nobr>操作</nobr>-->
<!--            </th>-->
          </tr>
        </template>
        <template partial='body'>
          <td  style="text-align: center;"><input type="checkbox" onClick="event.cancelBubble = true" :checked="$parent.$parent.$parent.isChecked(row.id)"  @change="$parent.$parent.$parent.setCheckes(row.id)" /></td>
          <td  style="text-align: center;">{{ row.f_checker_name }}</td>
          <td  style="text-align: center;">{{ row.f_check_book_name }}</td>
          <td  style="text-align: center;">{{ row.f_residential_area }}</td>
          <td  style="text-align: center;">{{ row.f_street }}</td>
          <td  style="text-align: center;">{{ row.f_slice_area }}</td>
<!--          <td  style="text-align: center;">{{ row.f_check_book_type }}</td>-->
          <td  style="text-align: center;">{{ row.f_user_type }}</td>
          <td  style="text-align: center;">{{ row.f_create_date }}</td>
          <td  style="text-align: center;">{{ row.f_create_person }}</td>
          <td  style="text-align: center;">{{ row.f_run_date }}</td>
          <td  style="text-align: center;">{{ row.f_around_time }}{{ row.f_around_unit }}</td>
          <td  style="text-align: center;"><button @click.stop="$parent.$parent.$parent.details(row)" class="btn btn-link"><b>{{row.num2}}</b></button></td>
<!--          <td  style="text-align: center;">{{ row.xiafa }}</td>-->
<!--          <td  style="text-align: center;">{{ row.f_user_type =='民用'?row.num-row.xiafa:row.num4-row.xiafa }}</td>-->
<!--          <td  style="text-align: center;">{{ row.yijian }}</td>-->
<!--          <td  style="text-align: center;">{{ row.weijian }}</td>-->
<!--          <td  v-show="row.f_check_book_type!='小区'" style="text-align: center;"><button class="button_spacing button_search-1" @click.stop='$parent.$parent.$parent.send(row)'>下发</button></td>-->
        </template>
      </data-grid>
    </criteria-paged>
    <modal :show.sync="showModal" :backdrop="false" id="checkbookEntryShow">
      <article slot="modal-body" class="modal-body">
        <check-book-entry v-if="showModal" @select-changed="selectedEntry"></check-book-entry>
      </article>
      <footer slot="modal-footer">
      </footer>

    </modal>

    <modal :show.sync="showModal2" v-if="showModal2" :backdrop="false" id="showModal2">
      <article slot="modal-body" class="modal-body">
        <form class="form-horizontal" novalidate>
          <div class="row" style="margin-top: 10px">
            <div class="col-sm-12 form-group"  style="margin: 0">
              <label class="font_normal_body">网格员</label>
              <v-select :value.sync="modalData.f_checker_name"
                        style="width: 60%"
                        class="select_list select" :value-single="false"
                        :multiple="true" :search="true"
                        :options='checkerNames' placeholder=''
                        close-on-select></v-select>
            </div>
<!--            <div class="form-group col-sm-12"  style="margin-top: 20px" :class="[$v.f_user_type.required ? 'has-error' : '']">-->
<!--              <label class="font_normal_body">用户类型</label>-->
<!--              <v-select :value.sync="modalData.f_user_type" v-model='modalData.f_user_type'-->
<!--                        :value-single="true" style="width: 60%"-->
<!--                        class="select_list select"-->
<!--                        :options='userTypes' placeholder=''-->
<!--                        close-on-select></v-select>-->
<!--            </div>-->
<!--            <div class="form-group col-sm-12"  style="margin-top: 20px" :class="[$v.f_responsible_person.required ? 'has-error' : '']">-->
<!--              <label class="font_normal_body">负&nbsp;责&nbsp;人</label>-->
<!--              <input type="text" class="input_search" v-model="modalData.f_responsible_person"-->
<!--                     style="width: 60%" v-validate:f_responsible_person='{ required: true }'>-->
<!--            </div>-->
<!--            <div class="form-group col-sm-12"  style="margin-top: 20px">-->
<!--              <label class="font_normal_body">执行日期</label>-->
<!--              <datepicker-->
<!--                :value.sync="modalData.f_run_date"-->
<!--                style="width: 60%"-->
<!--                :format="'yyyy-MM-dd'"-->
<!--                v-model="modalData.f_run_date"-->
<!--              >-->
<!--              </datepicker>-->
<!--            </div>-->
<!--            <div class="form-group col-sm-12"  style="margin-top: 20px">-->
<!--              <label class="font_normal_body">执行周期</label>-->
<!--              <input type="number" class="input_search" v-model="modalData.f_around_time"-->
<!--                     style="width: 60%"  >-->
<!--            </div>-->
<!--            <div class="form-group col-sm-12"  style="margin-top: 20px">-->
<!--              <label class="font_normal_body">周期单位</label>-->
<!--              <v-select :value.sync="modalData.f_around_unit" v-model='modalData.f_around_unit'-->
<!--                        :value-single="true" style="width: 60%"-->
<!--                        class="select_list select"-->
<!--                        :options='aroundUnit' placeholder=''-->
<!--                        close-on-select></v-select>-->
<!--            </div>-->
          </div>
        </form>
      </article>
      <footer slot="modal-footer">
        <div style="height: 50px;">
          <button @click="confirm()" style="margin-right: 20px;float: right" class="button_search">确认</button>
          <button @click="close()" style="margin-right: 20px;float: right" class="button_clear">取消</button>
        </div>
      </footer>
    </modal>

    <modal :show.sync="showSendModal" :backdrop="false" width="90%" height="90%">
      <article slot="modal-body" class="modal-body" style="height: 80vh">
        <check-book-search-user-list  v-if="showSendModal" :row="checkBookRow" :bookrow="checkBookRow" :needprops="needprops":userlogin="userlogin"></check-book-search-user-list>
      </article>
      <footer slot="modal-footer">
      </footer>

    </modal>
    <work-busy :is-busy="loading"></work-busy>
  </div>
</template>

<script>
import {PagedList} from 'vue-client'
import {HttpResetClass} from 'vue-client'
import bus from '../../../bus'
import * as Util from "../../../components/Util";
export default {
  title: '安检册管理',
  data () {
    return {
      loading:true,
      showSendModal:false,
      searchData: {
        condition: '1=1'
      },
      showCaoZuo:false,
      busy:false,
      userlogin:{
        id:this.$login.f.id,
        name:this.$login.f.name,
        orgid:this.$login.f.orgid,
        orgstr:this.$login.f.orgs,
      },
      checkAll:false,
      checkerNames:[],
      showModal2:false,
      modalData:{},
      checkBooks:[],
      bookTypes: [{label: '全部', value: ''}, {label: '用户', value: '用户'}, {label: '小区', value: '小区'}],
      userTypes: [{label: '全部', value: ''}, {label: '民用', value: '民用'}, {label: '非民用', value: '非民用'}],
      aroundUnit: [{label: '年', value: '年'}, {label: '月', value: '月'}, {label: '日', value: '日'}],
      showModal:false,
      model: new PagedList('rs/sql/QueryCheckBook', 20),
      checkBookRow:{},
      tempCondition:'1=2',
      checkes:[],
      checkBook :{
        f_check_book_name: '',
        f_run_date: '',
        f_around_time: '',
        f_around_unit: '',
        f_create_date: '',
        f_create_person: '',
        f_orgid: '',
        f_checker_name: ''
      }
    }
  },
  props: {
    style: {
      type: String,
      default: 'col-sm-2 form-group'
    },
    style2: {
      type: String,
      default: 'col-sm-4 form-group'
    },
    needprops:{
      type: Object,
      default:{}
    },
    showtype:{
      type: String
    }
  },
  ready () {
    setTimeout(() => {
      this.loading = false;
    }, 1000)
    bus.$on('fresh-main',()=>{
      this.$refs.paged.$refs.criteria.search()
    })
    this.freshCheckBook()
    this.initCheckNames()
  },
  beforeDestroy() {
    //tag
    bus.$off('fresh-main')
  },
  methods: {
    initCheckNames(){
      new HttpResetClass().load('POST',`/rs/sql/tel_singleTable_OrderBy`, {data: {
          items: '*',
          tablename: 't_user',
          condition: `state = '在职' and rolestr like '%网格员%'`,
          orderitem: 'id'
        }}, {resolveMsg: null, rejectMsg: null}).then((res) => {
        res.data.forEach(user=>{
          this.checkerNames.push({label: user.name, value: user.name})
        })
      })
    },
    async confirm() {
      if (!this.checkAll){
        if (this.checkes.length == 0){
          this.$showMessage('请选择需要修改的数据');
          return
        }
      }
      if (!this.modalData.f_checker_name) {
        this.$showMessage('请选择网格员');
        return;
      }
      let condition = `()`
      let check_name = this.modalData.f_checker_name.toString()
      if (this.checkAll){
        this.busy = true
        if (this.checkes.length > 0){
          this.tempCondition += ` and tcb.id not in (${this.checkes.join(',')})`
        }
        new HttpResetClass().load('post','rs/sql/QueryCheckBook',{data:{condition:this.tempCondition}}).then(response=>{
          this.busy = false
          if (response.data.length > 0){
            condition = `(${response.data.map(item => item.id).join(',')})`
            this.refreshCheckBook(condition,check_name)
          }else {
            this.$showMessage('无可修改数据');
            this.modalData.f_checker_name = []
            this.close()
          }
        }).catch(error=>{
          this.busy = false
          console.error('查询异常')
        })
      }else {
        condition = `(${this.checkes.join(',')})`
        this.refreshCheckBook(condition,check_name)
      }
    },
    refreshCheckBook(condition,check_name){
      this.busy = true
      new HttpResetClass().load('POST', 'rs/logic/runSQL', {data: {sql: `update t_check_book set f_checker_name = '${check_name}' where id in ${condition}`}},
        {resolveMsg: null, rejectMsg: null}).then(()=>{
        this.busy = false
        this.$showMessage(`修改成功`)
        this.modalData.f_checker_name = []
        this.$refs.paged.$refs.criteria.search()
        this.close()
      }).catch(()=>{
        this.busy = false
        this.$showMessage(`修改失败`)
      })
    },
    close(){
      this.checkAll = false
      this.showModal2 = false
      this.checkes = []
      this.modalData ={}
    },
    isChecked(v) {
      // 如果全选，不在的按选中算，否则，在的按选中算
      if (this.checkAll) {
        return this.checkes.indexOf(v) == -1
      } else {
        return this.checkes.indexOf(v) != -1
      }
    },
    setCheckes(id) {
      let index=this.checkes.indexOf(id)
      if(index<0){
        this.checkes.push(id)
      }else{
        this.checkes.splice(index,1)
      }
    },
    send(row){
      console.log("7758521",row)
      this.checkBookRow = row
      this.showSendModal = true
    },
    freshCheckBook () {
      this.checkBooks = []
      new HttpResetClass().load('POST', `/rs/sql/safe_singleTable_OrderBy?pageNo=1&pageSize=999999`, {
        data: {
          items: 'id,f_check_book_name',
          tablename: 't_check_book',
          condition: this.$refs.paged.$refs.criteria.model.f_orgid?`f_orgid in ${this.$refs.paged.$refs.criteria.model.f_orgid} and f_user_type ='${this.showtype}' `:`f_user_type ='${this.showtype}'`,
          orderitem: 'id desc'
        }
      }, {resolveMsg: null, rejectMsg: null}).then(res => {
        this.checkBooks.push({label: '全部', value: ''})
        res.data.forEach(ress => {
            this.checkBooks.push({
              label: ress.f_check_book_name,
              value: ress.id
            })
        })
      })
    },
    selectedEntry(){
      console.log("666666666666666666")
    },
    details(row){
      this.$emit('showdetails' ,row)
    },
    add(){
      this.$emit('addbook')
    },
    ok (){
      //tag
      let http = new HttpResetClass()
      http.load('POST', 'rs/logic/safeEntity', {data:{tableName:'t_check_book',entityData:this.checkBook}},
        {resolveMsg: '更新片区信息成功', rejectMsg: '保存片区信息成功'}).then(res=>{
          if (res.data.code===200){
            this.$showMessage('修改成功')
            this.showModal = false
            this.checkBook= {}
          }
      })
    },
    cancel () {
      this.showModal = false
      this.checkBook= {}
    },
    updateCheckBook(val){
      this.checkBook=val
      this.showModal = true
    },
    search (args) {
      // //tag
      this.$parent.showItem = false
      this.$parent.showItemUser = false
      args.condition += ` and f_orgid in ${this.model.f_filialeids}`
      args.condition += ` and tcb.f_user_type ='${this.showtype}' `
      this.tempCondition = args.condition
      return this.model.search(args.condition, args.model)
    },
    getRes (obj) {
      this.model.f_filialeids = this.$login.convertToIn(obj.resids)
    },
    async deleteCheckBook (val) {
      try {
        //tag
        let http = new HttpResetClass()
        let upAddress = `update t_user_address set f_check_book_id = null where f_check_book_id = '${val.id}'`
        let delCheckBook= `delete from t_check_book where id ='${val.id}'`
        await http.load('POST', 'rs/logic/runSQL', {data: {sql: upAddress}},
          {resolveMsg: null, rejectMsg: '删除片区失败'})
        await http.load('POST', 'rs/logic/runSQL', {data: {sql: delCheckBook}},
          {resolveMsg: null, rejectMsg: '删除片区失败'})
        this.$showMessage('删除成功')
        this.$refs.paged.$refs.criteria.search()
      }catch (e) {
        this.$showMessage('删除失败',e)
      }
    }
  },

  watch: {
    'model.rows'(val){
      console.log("997997",val)
      this.showCaoZuo = val.filter(item=>item.f_check_book_type!='小区').length>0
    }
  },
  computed: {
    selected () {
      return this.$refs.paged.$refs.grid.selected
    }
  }
}
</script>
<style scoped>
.newcolor {
  color: red;
}

.table th {
  background-color: #f2f6fa;
  color: black;
}
</style>
<style lang="less">
#checkbookEntryShow {
  .modal-dialog {
    width: 80%;
  }
}
</style>
