<template>
  <div class="flex-row">
    <div class="basic-main">
      <criteria-paged :model="model" v-ref:paged>
        <criteria partial='criteria' class="search_area" @condition-changed='$parent.selfSearch' v-ref:criteria>
          <div novalidate class="form-horizontal select-overspread container-fluid auto" partial>
            <div class="row">

                <div class="col-sm-3 form-group" style="margin-bottom: 0px">
                  <label class="font_normal_body">公&emsp;&emsp;司</label>
                  <right-tree-safe  @re-res="$parent.$parent.getResm" v-model="model.f_orgid" condition="ta.f_orgid in {}"></right-tree-safe>
              </div>
              <div class="form-group col-sm-3">
                <label class="font_normal_body">小区名称</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-3">
                <label class="font_normal_body">地址</label>
                <input type="text" class="input_search" v-model="model.f_area_address"
                       style="width: 60%" placeholder="地址" condition="f_area_address like '%{}%'">
              </div>
              <div class="form-group col-sm-3">
                <label class="font_normal_body">是否在册</label>
                <v-select :value.sync="model.f_is_checkbook" v-model='model.f_is_checkbook'
                          :value-single="true" style="width: 60%"
                          class="select_list select"
                          @change="$parent.$parent.changeState"
                          :options='$parent.$parent.isCheckBook' placeholder='有无所属片区'
                          close-on-select
                          condition="{}"></v-select>
              </div>
              <div class="form-group col-sm-3">
                <button class="button_spacing button_search" @click="search()">查询</button>
<!--                <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 class="list_area table_sy" style="overflow: hidden" :model="model" partial='list' v-ref:grid>
          <template partial='head'>
            <tr @dblclick.stop="">
              <th>
                <nobr><input type="checkbox" v-model="$parent.$parent.$parent.bookAll"></input>全选</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" :checked="$parent.$parent.$parent.checkModel(row)"
                           @change="$parent.$parent.$parent.checkChange(row, $event)"></input>
              </nobr>
            </td>
            <td style="text-align: center">{{ row.f_pcd }}</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_residential_area }}</td>
            <td style="text-align: center">{{ row.f_area_address }}</td>
            <td style="text-align: center">{{ row.f_check_book_name }}</td>
          </template>
        </data-grid>
      </criteria-paged>
    </div>
    <modal :show.sync="showModal" :backdrop="false">
      <div slot="modal-header" class="modal-header">
        <h4 class="modal-title">
          创建片区
        </h4>
      </div>
      <div slot="modal-body" class="modal-body">
        <div v-if="true">
          <div class="row" style="margin-top: 10px">

            <div class="col-sm-12 form-group"  style="margin: 0">
              <role-selector-safe
                @re-res="getRes"
                role-name="安检员"
                role-lable="安&nbsp;检&nbsp;员&nbsp;"
                :value.sync="checkBook.f_checker_name"
                v-model="checkBook.f_checker_name">
              </role-selector-safe>
            </div>
            <div class="form-group col-sm-6"  style="margin-top: 20px">
              <label class="font_normal_body">片区名</label>
              <input type="text" class="input_search" v-model="checkBook.f_check_book_name"
                     style="width: 60%"  >
            </div>
            <div class="form-group col-sm-6"  style="margin-top: 20px">
              <label class="font_normal_body">执行日期</label>
              <datepicker
                :value.sync="checkBook.f_run_date"
                style="width: 60%"
                :format="'yyyy-MM-dd'"
                v-model="checkBook.f_run_date"
              >
              </datepicker>
            </div>
            <div class="form-group col-sm-6"  style="margin-top: 20px">
              <label class="font_normal_body">执行周期</label>
              <input type="number" class="input_search" v-model="checkBook.f_around_time"
                     style="width: 60%"  >
            </div>
            <div class="form-group col-sm-6"  style="margin-top: 20px">
              <label class="font_normal_body">周期单位</label>
              <v-select :value.sync="checkBook.f_around_unit" v-model='checkBook.f_around_unit'
                        :value-single="true" style="width: 60%"
                        class="select_list select"
                        :options='aroundUnit' placeholder=''
                        close-on-select></v-select>
            </div>
          </div>
        </div>
      </div>
      <div slot="modal-footer" class="modal-footer" style="text-align: center">
        <button class="button_search" style="margin-right: 20px" @click="ok">确认</button>
        <button class="button_search" @click="cancel">取消</button>
      </div>
    </modal>
    <modal :show.sync="showModal2" :backdrop="false">
      <div slot="modal-header" class="modal-header">
        <h4 class="modal-title">
          添加用户
        </h4>
      </div>
      <div slot="modal-body" class="modal-body">
        <div v-if="true">
          <div class="row" style="margin-top: 10px">
            <div class="form-group col-sm-12"  style="margin-top: 20px">
              <label class="font_normal_body">安&ensp;检&ensp;册</label>
              <v-select :value.sync="selectBook" v-model='selectBook'
                        :value-single="true" style="width: 80%"
                        class="select_list select"
                        :options='checkBooks' placeholder=''
                        close-on-select></v-select>
            </div>
          </div>
        </div>
      </div>
      <div slot="modal-footer" class="modal-footer" style="text-align: center">
        <button class="button_search" style="margin-right: 20px" @click="ok2">确认</button>
        <button class="button_search" @click="cancel2">取消</button>
      </div>
    </modal>
    <modal :show.sync="showModal3" :backdrop="false">
      <div slot="modal-header" class="modal-header">
        <h4 class="modal-title">
          调整用户
        </h4>
      </div>
      <div slot="modal-body" class="modal-body">
        <div v-if="true">
          <div class="row" style="margin-top: 10px;text-align: center">
            <div class="form-group col-sm-12"  style="margin-top: 20px">
              <label class="font_normal_body">安&ensp;检&ensp;册</label>
              <v-select :value.sync="selectBook" v-model='selectBook'
                        :value-single="true" style="width: 80%"
                        class="select_list select"
                        :options='checkBooks' placeholder=''
                        close-on-select></v-select>
            </div>
          </div>
        </div>
      </div>
      <div slot="modal-footer" class="modal-footer" style="text-align: center">
        <button class="button_search" style="margin-right: 20px" @click="ok3">确认</button>
        <button class="button_search" @click="cancel3">取消</button>
      </div>
    </modal>

  </div>
</template>

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

export default {
  title: '片区管理',
  data () {
    let model = new PagedList('rs/sql/safe_singleTable_OrderBy', 20,{
        items: "'ta.*,tcb.f_check_book_name'",
        tablename: "'t_area ta left join t_check_book tcb on ta.f_check_book_id=tcb.id'",
        orderitem: "'id desc'"
      })
    return {
      model: model,
      criteriaShow: false,
      excelHeaders: {},
      checkBooks: [],
      f_orgid: '',
      bookAll: false,
      bookList: [],
      selectBook:'',
      // init:false,
      aroundUnit: [{label: '年', value: '年'}, {label: '月', value: '月'}, {label: '日', value: '月'}],
      isCheckBook: [{label: '全部', value: ''}, {label: '是', value: 'f_check_book_id is not null'}, {label: '否', value: 'f_check_book_id is null'}],
      isSearch: false,
      checkBook: {
        f_check_book_name: '',
        f_run_date: '',
        f_around_time: '',
        f_around_unit: '',
        f_create_date: Util.toStandardDateString(),
        f_create_person: this.$login.f.name,
        f_orgid: '',
        f_checker_name: ''
      },
      showModal: false,
      showModal2: false,
      showModal3: false
    }
  },
  beforeDestroy() {
    //tag
    bus.$off('fresh-area')
  },
  computed: {
    searchData () {
      return {condition: this.model.condition}
    },
    bookCondition () {
      return this.model.condition
    },
    isCreateBook () {
      return this.$refs.paged.$refs.criteria.model.f_is_checkbook === 'f_check_book_name is null'
    },
    isChangeBook () {
      return this.$refs.paged.$refs.criteria.model.f_is_checkbook === 'f_check_book_name is not null'
    }
  },
  watch:{
    'bookList'(){
      this.$emit('book-list',this.bookList)
    },
    'bookAll'(val){
      if(!val){
        this.bookList=[]
      }
      this.$emit('book-all',this.bookAll)
    }
  },
  methods: {
    async ok2() {
      if (!this.selectBook) {
        this.$showMessage('请选择片区')
        return
      }
      if (this.isSearch && (this.bookAll || this.bookList.length > 0) && this.model.rows.length > 0) {
        let userCondition = ''
        if (this.bookList.length < 1) {
          //tag
          userCondition = this.bookCondition
        } else {
          //tag)

          userCondition = JSON.stringify(this.bookList).substring(JSON.stringify(this.bookList).indexOf('[') + 1, JSON.stringify(this.bookList).indexOf(']'))
          userCondition = 'tui.f_userinfo_id in (' + userCondition + ')'
          //tag
        }
        let addUser = `update t_user_address set f_check_book_id ='${this.selectBook}'
        FROM
            t_userinfo tui
                LEFT JOIN t_userfiles tuf ON tui.f_userinfo_id= tuf.f_userinfo_id
                LEFT JOIN t_user_address tua ON tuf.f_userinfo_id = tua.f_userinfo_id
                LEFT JOIN t_check_book tcb ON tua.f_check_book_id= tcb.id
        WHERE
                tui.f_user_state = '正常'
          AND ( tuf.f_table_state= '正常' OR tuf.f_table_state= '停用' )
          AND ${userCondition}`
        await new HttpResetClass().load('POST', 'rs/logic/runSQL', {data: {sql: addUser}},
          {resolveMsg: null, rejectMsg: '添加用户失败'})
        this.$showMessage('添加用户成功')
        this.selectBook = ''
        this.bookAll = false
        this.bookList = []
        this.showModal2 = false
        this.$refs.paged.$refs.criteria.search()
      }
    },
    async ok3() {
      if (!this.selectBook) {
        this.$showMessage('请选择片区')
        return
      }
      if (this.isSearch && (this.bookAll || this.bookList.length > 0) && this.model.rows.length > 0) {
        let userCondition = ''
        if (this.bookList.length < 1) {
          //tag
          userCondition = this.bookCondition
        } else {
          //tag)

          userCondition = JSON.stringify(this.bookList).substring(JSON.stringify(this.bookList).indexOf('[') + 1, JSON.stringify(this.bookList).indexOf(']'))
          userCondition = 'tui.f_userinfo_id in (' + userCondition + ')'
          //tag
        }
        let upUser = `update t_user_address set f_check_book_id ='${this.selectBook}'
        FROM
            t_userinfo tui
                LEFT JOIN t_userfiles tuf ON tui.f_userinfo_id= tuf.f_userinfo_id
                LEFT JOIN t_user_address tua ON tuf.f_userinfo_id = tua.f_userinfo_id
                LEFT JOIN t_check_book tcb ON tua.f_check_book_id= tcb.id
        WHERE
                tui.f_user_state = '正常'
          AND ( tuf.f_table_state= '正常' OR tuf.f_table_state= '停用' )
          AND ${userCondition}`
        await new HttpResetClass().load('POST', 'rs/logic/runSQL', {data: {sql: upUser}},
          {resolveMsg: null, rejectMsg: '调整用户失败'})
        this.$showMessage('调整用户成功')
        this.selectBook = ''
        this.bookAll = false
        this.bookList = []
        this.showModal3 = false
        this.$refs.paged.$refs.criteria.search()
      }
    },
    cancel2(){
      this.selectBook = ''
      this.bookAll = false
      this.bookList = []
      this.showModal2 = false
      this.$refs.paged.$refs.criteria.search()
    },
    cancel3(){
      this.selectBook = ''
      this.bookAll = false
      this.bookList = []
      this.showModal3 = false
      this.$refs.paged.$refs.criteria.search()
    },
    addUser () {
      if (!this.isCreateBook) {
        this.$showMessage('请选择查询未划分片区的用户')
        return
      }
      if (this.isSearch && (this.bookAll || this.bookList.length > 0) && this.model.rows.length > 0) {
        this.showModal2 = true
        this.freshCheckBook()
        return
      }
      this.$showMessage('请选择用户')
    },
    upUser () {
      if (!this.isChangeBook) {
        this.$showMessage('请选择查询已划分片区的用户')
        return
      }
      if (this.isSearch && (this.bookAll || this.bookList.length > 0) && this.model.rows.length > 0) {
        this.showModal3 = true
        this.freshCheckBook()
        return
      }
      this.$showMessage('请选择用户')
    },
    async delUser () {
      if (!this.isChangeBook) {
        this.$showMessage('请选择查询已划分片区的用户')
        return
      }
      if (this.isSearch && (this.bookAll || this.bookList.length > 0) && this.model.rows.length > 0) {
        let userCondition= ''
        if (this.bookList.length < 1) {
          //tag
          userCondition = this.bookCondition
        } else {
          //tag)

          userCondition = JSON.stringify(this.bookList).substring(JSON.stringify(this.bookList).indexOf('[') + 1, JSON.stringify(this.bookList).indexOf(']'))
          userCondition = 'tui.f_userinfo_id in (' + userCondition + ')'
          //tag
        }
        let delUser= `update t_user_address set f_check_book_id =null
        FROM
            t_userinfo tui
                LEFT JOIN t_userfiles tuf ON tui.f_userinfo_id= tuf.f_userinfo_id
                LEFT JOIN t_user_address tua ON tuf.f_userinfo_id = tua.f_userinfo_id
                LEFT JOIN t_check_book tcb ON tua.f_check_book_id= tcb.id
        WHERE
                tui.f_user_state = '正常'
          AND ( tuf.f_table_state= '正常' OR tuf.f_table_state= '停用' )
          AND ${userCondition}`
        await new HttpResetClass().load('POST', 'rs/logic/runSQL', {data: {sql: delUser}},
          {resolveMsg: null, rejectMsg: '删除片区失败'})
        this.$showMessage('从片区删除所选用户成功')
        this.selectBook = ''
        this.bookAll = false
        this.bookList = []
        this.showModal3 = false
        this.$refs.paged.$refs.criteria.search()
        return
      }
      this.$showMessage('请选择用户')
    },
    beforeCreateBook () {
      if (!this.isCreateBook) {
        this.$showMessage('请选择查询未划分片区的用户')
        return
      }
      if (this.isSearch && (this.bookAll || this.bookList.length > 0) && this.model.rows.length > 0) {
        this.showModal = true
        return
      }
      this.$showMessage('请选择用户')
    },
    ok () {
      //tag)
      let condition = ''
      if (!this.checkBook.f_check_book_name) {
        return this.$showMessage('请填写册名')
      }
      if (!this.checkBook.f_checker_name) {
        return this.$showMessage('请选择安检员')
      }
      if (!this.checkBook.f_around_time || !this.checkBook.f_around_unit) {
        return this.$showMessage('请选填写周期信息')
      }
      if (!this.checkBook.f_run_date) {
        return this.$showMessage('执行日期')
      }
      if (this.bookList.length < 1) {
        //tag
        condition = this.bookCondition
      } else {
        //tag)

        condition = JSON.stringify(this.bookList).substring(JSON.stringify(this.bookList).indexOf('[') + 1, JSON.stringify(this.bookList).indexOf(']'))
        condition = 'tui.f_userinfo_id in (' + condition + ')'
        //tag
      }
      let data = {
        checkBook: this.checkBook,
        sqlStr: condition
      }
      new HttpResetClass().load('post', 'rs/logic/AddCheckBook', {data}).then(res => {
        //tag)
        if (res.data.id) {
          this.$showMessage('创建成功')
          this.showModal = false
          this.isSearch = false
          this.bookList = []
          this.bookAll = false
          this.freshCheckBook()
          this.$refs.paged.$refs.criteria.search()
        }
      })
    },
    changeState (val) {
      //tag
      //tag
      this.bookAll = false
      this.bookList = []
      if (this.$refs.paged.$refs.criteria.model.f_orgid){
        this.$refs.paged.$refs.criteria.search()
      }
    },
    cancel () {
      this.bookAll = false
      this.bookList = []
      this.showModal = false
      this.$refs.paged.$refs.criteria.search()
    },
    checkModel (row) {
      if (this.bookAll) {
        //tag)
        return true
      } else {
        if (this.bookList.findIndex(res => res === row.id) !== -1) {
          return true
        } else {
          return false
        }
      }
    },
    checkChange (row, e) {
      //tag
      if (e.target.checked) {
        this.bookList.push(row.id)
      } else {
        this.bookList.splice(this.bookList.findIndex(res => res === row.id), 1)
      }
      // //tag)
    },
    getRes (obj) {
      this.checkBook.f_orgid = obj.resids[0]
    },
    getResm (obj) {
      this.$refs.paged.$refs.criteria.model.f_orgid = this.$login.convertToIn(obj.resids)
    },
    hidden () {
      this.criteriaShow = !this.criteriaShow
    },
    selfSearch (args) {
      this.isSearch = true
      this.bookAll = false
      this.bookList = []

      console.log("查询66666666666666666")
      this.$emit('book-condition',args.condition)
      // if (this.$refs.paged.$refs.criteria.model.f_orgid){
      //   args.condition += `f_orgid in ${this.$refs.paged.$refs.criteria.model.f_orgid}`
      // }
      this.model.search(args.condition, args.model)
    },
    freshCheckBook () {
      this.checkBooks = []
      new HttpResetClass().load('POST', `/rs/sql/safe_singleTable_OrderBy`, {
        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}`:'1=1',
          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
          })
        })
      })
    }
  },

  ready () {
    bus.$on('fresh-area',()=>{
      console.log("进入方法",this.bookAll,this.bookList)
      this.bookAll = false
      this.bookList = []
      this.$refs.paged.$refs.criteria.search()
    })
    this.$refs.paged.$refs.criteria.model.f_is_checkbook = 'f_check_book_id is null'
    //tag
    // this.init=true
    this.freshCheckBook()
  }
}
</script>
<style  scoped>
/*.btn-group > .btn:first-child {*/
/*  margin-left: 0;*/
/*  width: 100%;*/
/*}*/
</style>
