<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.search' v-ref:criteria>
          <!--<div novalidate class="form-inline auto" partial>-->
          <div novalidate class="form-horizontal select-overspread container-fluid auto" partial>
            <div class="row">
              <div class="col-sm-3 " style="width: 20%">
                <label class="font_normal_body"  for="c_plan_year">选择年份</label>
                <v-select  class="select select_list"  id="c_plan_year" :value.sync="$parent.$parent.model.c_plan_year" style=";width: 60%"
                           :options='$parent.$parent.c_year_list' close-on-select clear-button></v-select>
              </div>
              <div class="col-sm-3 " style="width: 20%">
                <label class="font_normal_body"  for="c_plan_month">选择月份</label>
                <v-select class="select select_list" id="c_plan_month" :value.sync="$parent.$parent.model.c_plan_month" style=";width: 60%"
                          :options='$parent.$parent.c_month_list' close-on-select clear-button></v-select>
              </div>
              <div class="col-sm-3 " style="width: 20%">
                <label class="font_normal_body" >计划名称</label>
                <input type="text"class="input_search"  style="width: 60%;" v-model="model.f_plan_name" id="f_plan_name"
                       placeholder="计划名称" condition="c.f_plan_name like '%{}%'">
              </div>
              <div class="col-sm-3 " style="width: 20%">
                <label class="font_normal_body" >小区名称</label>
                <input type="text" class="input_search"  style="width: 60%;" v-model="model.f_residential_area" id="f_residential_area"
                       placeholder="小区" condition="f_residential_area like '%{}%'">
              </div>
              <div class="col-sm-3" style = "width: 20%;float:right;">

                <div class="button_spacing" style = "float:right;margin-top: 8px"
                     :class="{'button_shrink_top':$parent.$parent.criteriaShow,'button_shrink_bottom'
                     :!$parent.$parent.criteriaShow}"
                     @click="$parent.$parent.hidden()">
                </div>
                <button type="button" class="button_new button_spacing" style = "float:right; margin-top: 8px" @click="$parent.$parent.adjust()" >调整</button>
                <button type="button" class="button_search button_spacing" style = "float:right; margin-top: 8px" @click="search()" >查询</button>

              </div>



            </div>
            <div class="row" v-if="$parent.$parent.criteriaShow">

              <div class="col-sm-3 " style="width: 20%">
                <label class="font_normal_body" >用户编号</label>
                <input type="text" class="input_search"  style="width: 60%;" v-model="model.f_userinfo_code"
                       placeholder="用户编号" condition="i.f_userinfo_code = '{}'">
              </div>

              <div class="col-sm-3 " style="width: 20%">
                <label  class="font_normal_body" >用户姓名</label>
                <input type="text" class="input_search"  style="width: 60%;" v-model="model.f_user_name"
                       placeholder="用户姓名" condition="i.f_user_name = '{}'">
              </div>

              <div class="col-sm-3 " style="width: 20%">
                <label class="font_normal_body" >安&nbsp;&nbsp;检&nbsp;员</label>
                <input type="text" class="input_search"  style="width: 60%;" v-model="model.f_checker"
                       placeholder="安检员姓名" condition="c.f_checker like '%{}%'">
                <!--                <v-select class="select select_list"
                                          :value.sync="model.f_checker_id" v-model='model.f_checker_id'
                                          :value-single="true"
                                          :options='$parent.$parent.checkersid' placeholder='安检员'
                                          close-on-select style=";width: 60%"
                                          condition="c.f_checker_id = '{}'"></v-select>-->
              </div>
              <div class="col-sm-3 " style="width: 20%">
                <label class="font_normal_body" >安检状态</label>
                <v-select class="select select_list"
                          :value.sync="$parent.$parent.f_check_state" v-model='$parent.$parent.f_check_state'
                          :value-single="true"
                          :options='$parent.$parent.check_versions' placeholder='到访不遇次数'
                          close-on-select style=";width: 60%"
                ></v-select>
              </div>
            </div>
          </div>
        </criteria>
        <data-grid class="list_area table_sy" partial='list' :model="model" style="overflow: hidden" v-ref:grid >
          <template partial='head'>
            <tr>
              <th><nobr><input type="checkbox" v-model="$parent.$parent.$parent.checkAll"/> 全选</nobr></th>
              <th>计划名称</th>
              <th>用户编号</th>
              <th>用户名</th>
              <th>小区名称</th>
              <th>地址</th>
              <th>安检员</th>
              <th>到访不遇次数</th>
              <!--<th>操作</th>
              <th>标记</th>-->
            </tr>
          </template>
          <template partial='body'>
            <td style="text-align: center"><nobr><input type="checkbox" onClick="event.cancelBubble = true" :checked="$parent.$parent.$parent.isChecked(row.id)"  @change="$parent.$parent.$parent.setCheckes(row.id)"></nobr></td>
            <td style="text-align: center">{{row.f_plan_name}}</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_residential_area}}</td>
            <td style="text-align: center">{{row.f_address}}</td>
            <td style="text-align: center">{{row.f_checker}}</td>
            <td style="text-align: center">{{row.f_check_version}}</td>
          </template>
        </data-grid>
      </criteria-paged>
      <modal :show.sync="showModal" v-if="showModal" v-ref:modal>
        <div slot="modal-header" class="modal-header">
          <h4 class="modal-title">
            选择计划
          </h4>
        </div>
        <div slot="modal-body" class="modal-body">
          <plan-chooser-ts :f.sync="fun" :safetype="safetype"  v-ref:chooser></plan-chooser-ts>
        </div>
        <div slot="modal-footer" class="modal-footer" style="text-align: center">
          <button  class="button_search button_spacing" @click="ok()">确认</button>
          <button  class="button_clear button_spacing" @click="cancel()">取消</button>
        </div>
      </modal>
    </div>
  </div>

</template>

<script>
  import { PagedList } from 'vue-client'
  import { HttpResetClass } from 'vue-client'
  import * as Util from '../../../Util'
  import Vue from 'vue'
  import co from  'co'

  let select = function * (self) {
    let getGasman = yield self.$resetpost('/rs/search', {
      source: 'this.getParentByType($department$).getAllChildrens().where(row.getAttributes().get($rolestr$).indexOf($安检员$) != -1))',
      userid: self.$login.f.id
    }, {resolveMsg: null, rejectMsg: null})
    console.log('获取安检员', getGasman)
    getGasman.data.forEach((checker)=>{
      self.checkersid.push({label:checker.name,value:checker.id})
    })
    self.checkersid.push({label:'全部',value:''})
  }

  let syncDelete = function * (self,row) {
    yield self.$resetpost('api/af-safecheck/logic/deleteCheckPlanItemTS', {id:row.id },{
      warnMsg: '删除数据不可恢复，确认删除吗？',
      resolveMsg: '恭喜！删除成功！',
      rejectMsg: '删除失败：'
    })
    self.$refs.paged.$refs.criteria.search()
  }

  export default {
    title: '计划调整(未整合)',
    data () {
      let options = []
      let year = (new Date()).getFullYear()
      for(let i = year - 8; i <= year +1; i++ )
        options.push({label: i+'', value: i+''})
      let moptions = []
      for(let i=1; i<=12; i++)
        moptions.push({label: i + '', value: i + ''})
      let model = new PagedList('api/af-safecheck/sql/FetchPlanItemByYearMonthCheckerIdTS', 20,
        {f_filialeid: 'this.f_filialeid', f_plan_year: 'this.c_plan_year[0]', f_plan_month: 'this.c_plan_month[0]'})
      model.c_plan_year = [year+'']
      model.c_plan_month = [moptions[new Date().getMonth()].value]
      model.chosenOrg = {id:0}
      return {
        showModal:false,
        checkedAll: false,
        checkrows: [],
        plan_id:'',
          criteriaShow:false,
        checkersid:[],
        fun:this.$login.f,
        safetype:'年度普检',
        checker:this.$login.f,
        leftCheckers:this.$parent.checkers,
        model: model,
        c_year_list: options,
        c_month_list: moptions,
        f_check_state:'',
        check_versions:[{label: '未检', value: '未检'},{label: '到访不遇一次', value: '到访不遇一次'},{label: '到访不遇两次', value: '到访不遇两次'}],
        checkAll:false,
        checkes:[]
      }
    },
    watch: {
      'checker'(){
        console.log("f_checker",this.checker)
        this.model.chosenOrg = this.checker[0]
      }
    },
    methods:{
      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)
        }
      },
      ok(){
        if(!this.$refs.chooser.selectedRow.id){
          this.$showMessage('未选择目标计划!', ['confirm'])
          return
        }
        console.log(`选择目标计划id:${this.$refs.chooser.selectedRow.id}`)
        // 执行调整业务
        let condition1=this.model.params.condition
        if(this.model.params.f_filialeid){
          condition1+=` and i.f_filialeid='${this.model.params.f_filialeid}'`
        }
        if(this.model.params.f_plan_year){
          condition1+=` and c.f_plan_year='${this.model.params.f_plan_year}'`
        }
        if(this.model.params.f_plan_month){
          condition1+=` and c.f_plan_month='${this.model.params.f_plan_month}'`
        }
        let http = new HttpResetClass()
        http.load('POST', 'api/af-safecheck/logic/CheckerPlanAdjustTS', {
          data: {
            f_plan_id:this.$refs.chooser.selectedRow.id,
            condition:condition1,
            switchCheckAll:true,
            checkAll:this.checkAll,
            param:this.checkes,
            columnName:'i.id',
          }
        }, {resolveMsg: null, rejectMsg: null}).then((res) => {
          console.log(res.data)
          console.log("计划调整结果")
          //this.$showMessage(`共调整 ${this.checkrows.length} 个，其中${res.data.existitem}个在${this.$refs.chooser.selectedRow.f_plan_name}已存在，新增${res.data.updateitem}个！`)
          this.$showMessage('调整成功！')
          this.showModal = false
          this.checkAll = false
          this.checkes = []
          this.$refs.paged.$refs.criteria.search()
        })
      },
      hidden(){
        this.criteriaShow=!this.criteriaShow
      },
      cancel(){
        this.showModal = false
        this.$refs.chooser.model.rows=[]
        this.$refs.chooser.selectedRow={}
      },
      adjust(){   //  调整计划
        if(this.checkAll  ||  this.checkes.length>0){
          if(this.checkAll && this.model.rows.length==this.checkes.length){}
          this.showModal = true
        }else{
          this.$showMessage('请选择用户后，再进行调整!', ['confirm'])
        }
      },
      // 全选
      changeStates() {
        if (this.checkedAll) {
          this.checkrows = [];
          for (let i = 0; i < this.$refs.paged.model.rows.length; i++) {
            this.$set('$refs.paged.model.rows[' + i + '].checked', false)
          }
        } else {//实现全选
          for (let i = 0; i < this.$refs.paged.model.rows.length; i++) {
            this.$set('$refs.paged.model.rows[' + i + '].checked', true)
          }
          let _this = this
          let condition = this.$refs.paged.$refs.criteria.condition
          let url = this.model.url
          this.$resetpost(`${url}?pageSize=9999999`, {data:{condition:condition,f_filialeid: this.model.f_filialeid, f_plan_year: this.model.c_plan_year[0], f_plan_month: this.model.c_plan_month[0]}},{resolveMsg: null, rejectMsg: null}, -1).then(
            (respanse) => {
              if (respanse.data.length >= 5000) {
                this.$showMessage("数据量太大，请重新查询")
              } else {
                _this.checkrows = []
                for (let j = 0; j < respanse.data.length; j++) {
                  _this.checkrows.push(respanse.data[j])
                }
                console.log(_this.checkrows);
              }
            })
        }
      },
      search(args ){
        this.checkAll = false
        this.checkes = []
        /*if(this.f_check_version=='全部'){
          args.condition+= `and i.f_state ='未检' or (i.f_check_version and f_last_check_state='到访不遇')`
        }else */
        args.condition+=` and i.f_safecheck_type='年度普检'`
        if(this.f_check_state=='未检'){
          args.condition+= `and i.f_state='未检'`
        }else if(this.f_check_state=='到访不遇一次'){
          args.condition+= `and i.f_state='已检' and i.f_check_version='1' and i.f_last_check_state='到访不遇'`
        }else if(this.f_check_state=='到访不遇两次'){
          args.condition+= `and i.f_state='已检' and i.f_check_version='2' and i.f_last_check_state='到访不遇'`
        }
        this.model.search(args.condition, args.model)
        console.log('this.model---'+JSON.stringify(this.model))
      },
      delete(row){
        let gen = syncDelete(this,row)
        return co(gen)
      }
    },
    ready () {
      this.f_check_state='未检'
      this.model.id = this.$login.f.id
      this.model.f_subcompany = this.$login.f.f_fengongsi
      this.model.f_filialeid  = this.$login.f.orgid
      let gen = select(this)
      return co(gen)
    },
    watch:{
      'model.rows'() {
        for (let i = 0; i < this.$refs.paged.model.rows.length; i++) {
          var k = false
          for (let j = 0; j < this.checkrows.length; j++) {
            if (this.$refs.paged.model.rows[i].id == this.checkrows[j].id) {
              this.$set('$refs.paged.model.rows[' + i + '].checked', true)
              k = true
              continue
            }
          }
          if (!k) {
            this.$set('$refs.paged.model.rows[' + i + '].checked', false)
          }
        }
      },
      'checkAll'(val){
        this.checkAll=val;
        // 全选改变后，清空选中数据
        this.checkes = []
      }
    },
    computed: {
      selected () {
        return this.$refs.paged.$refs.grid.selected
      }
    }
  }
</script>
