<template>
  <div>

    <criteria-paged :model="model" v-ref:paged class="foot">
      <criteria partial='criteria'   @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="col-sm-4 form-group form-input-group" style="width: 25%">
            <label class="font_normal_body" for="c_plan_year">年&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;份</label>
            <v-select id="c_plan_year" :value.sync="$parent.$parent.model.c_plan_year" class="select"
                      :options='$parent.$parent.c_year_list' close-on-select clear-button></v-select>
          </div>
          <div class="col-sm-4 form-group form-input-group" style="width: 25%">
            <label class="font_normal_body " for="c_plan_month">月&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;份</label>
            <v-select id="c_plan_month" :value.sync="$parent.$parent.model.c_plan_month" class="select"
                      :options='$parent.$parent.c_month_list' close-on-select clear-button></v-select>
          </div>
          <div class="col-sm-4 form-group form-input-group" style="width: 25%">
            <label class="font_normal_body" for="f_residential_area">小&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;区</label>
            <input type="text" class="input_search" v-model="model.f_residential_area" id="f_residential_area"
                   placeholder="小区" condition="f_residential_area like '%{}%'" onfocus="this.placeholder=''"   onblur="this.placeholder='小区'">
          </div>
          <div class="col-sm-4 form-group form-input-group" style="width: 25%">
            <label class="font_normal_body">安&nbsp;&nbsp;检&nbsp;员</label>
            <v-select  :value.sync="model.f_checker_id" v-model='model.f_checker_id'
                      :value-single="true" class="select"
                      :options='$parent.$parent.checkersid' placeholder='安检员'
                      close-on-select
                      condition="c.f_checker_id = '{}'"></v-select>
          </div>
          <div class=" col-sm-4" style = "float:right;width: 25%">
            <button type="button" class="button_spacing button_search" @click="search()">查询</button>
            <button type="button" class="button_new button_spacing" @click="$parent.$parent.delrepeat()">去重</button>
            <button type="button" class="button_export button_spacing" @click="$parent.$parent.simdelrepeat()">一键去重</button>
          </div>
        </div>
      </criteria>
      <data-grid :model="model" partial='list' v-ref:grid  >
        <template partial='head'>
          <tr>
            <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" v-model="row.checked" v-bind:checked="row.checked"  @click="$parent.$parent.$parent.addChecked(row)"></nobr></td>
          <td>{{row.f_plan_name}}</td>
          <td>{{row.f_userinfo_code}}</td>
          <td>{{row.f_user_name}}</td>
          <td>{{row.f_residential_area}}</td>
          <td>{{row.f_address}}</td>
          <!--<td><span class="glyphicon glyphicon-trash" @click="$parent.$parent.$parent.delete(row)"></span></td>-->
          <!--<td>{{row.sign=='1'?'◆':''}}</td>-->
        </template>
      </data-grid>
    </criteria-paged>
    <modal :show.sync="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 :f.sync="fun"  v-ref:chooser></plan-chooser>
      </div>
      <div slot="modal-footer" class="modal-footer">
        <button  class="btn btn-success width-80" @click="ok()">确认</button>
        <button  class="btn btn-success width-80" @click="cancel()">取消</button>
      </div>
    </modal>
  </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($organization$).getChildByName($安检员$).getUsers()',
      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('rs/logic/deleteCheckPlanItem', {id:row.id },{
      warnMsg: '删除数据不可恢复，确认删除吗？',
      resolveMsg: '恭喜！删除成功！',
      rejectMsg: '删除失败：'
    })
    self.$refs.paged.$refs.criteria.search()
  }

  export default {
    name:'DelPlanRepeat',
    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('rs/sql/RepreatCheckPlan', 20,
        {f_subcompany: 'this.f_subcompany', 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:'',
        checkersid:[],
        fun:this.$login.f,
        checker:this.$login.f,
        leftCheckers:this.$parent.checkers,
        model: model,
        c_year_list: options,
        c_month_list: moptions
      }
    },
    watch: {
      'checker'(){
        console.log("f_checker",this.checker)
        this.model.chosenOrg = this.checker[0]
      }
    },
    methods:{
      ok(){
        if(!this.$refs.chooser.selectedRow.id){
          this.$showMessage('未选择目标计划!', ['confirm'])
          return
        }
        console.log(`选择目标计划id:${this.$refs.chooser.selectedRow.id}`)
        // 执行调整业务
        let http = new HttpResetClass()
        http.load('POST', 'rs/logic/CheckerPlanAdjust', {
          data: {
            f_plan_id:this.$refs.chooser.selectedRow.id,
            checkrows:this.checkrows
          }
        }, {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.$refs.chooser.model.rows=[]
          this.$refs.chooser.selectedRow={}
          this.$refs.chooser.model.f_checker_id=''
          this.showModal = false
          this.$refs.paged.$refs.criteria.search()
        })
      },
      //一键去重
      simdelrepeat(){
        var condition=''
        if(this.model.condition==null){
          condition='1=1'
        }else {
          condition=this.model.condition
        }
        var sqlcondition={
          condition:condition,
          f_plan_year:this.model.c_plan_year[0],
          f_plan_month:this.model.c_plan_month[0],
          f_subcompany:this.model.f_subcompany
        }
       console.log(sqlcondition,'测试请求sql')
       let http = new HttpResetClass()
        http.load('POST', 'rs/logic/deleteCheckPlanRepeat', {
          data: sqlcondition
        }, {resolveMsg: null, rejectMsg: null}).then((res) => {
          console.log(res.data)
          console.log("一键去重")
          this.$showMessage(`${res.data.mgs}`)
          this.$refs.chooser.model.rows=[]
          this.$refs.chooser.selectedRow={}
          this.$refs.chooser.model.f_checker_id=''
          this.showModal = false
          this.$refs.paged.$refs.criteria.search()
        })
      },
      //选择去重
      delrepeat(){
        if(this.checkrows.length<1){
          this.$showMessage(`请选择删除计划`)
          return
        }
        var condition=''
        if(this.model.condition==null){
          condition='1=1'
        }else {
          condition=this.model.condition
        }
        var sqlcondition={
          condition:condition,
          f_plan_year:this.model.c_plan_year[0],
          f_plan_month:this.model.c_plan_month[0],
          f_subcompany:this.model.f_subcompany,
          checked:this.checkrows
        }
        console.log(sqlcondition,'测试请求sql')
        let http = new HttpResetClass()
        http.load('POST', 'rs/logic/SeldeleteCheckPlanRepeat', {
          data: sqlcondition
        }, {resolveMsg: null, rejectMsg: null}).then((res) => {
          console.log(res.data)
          console.log("选择去重")
          if(res.data.code==200){
            this.$showMessage(`${res.data.mgs}`)
          }else {
            this.$showMessage(`去重成功,多计划用户保留最新计划!`)
          }
          this.$refs.chooser.model.rows=[]
          this.$refs.chooser.selectedRow={}
          this.$refs.chooser.model.f_checker_id=''
          this.showModal = false
          this.$refs.paged.$refs.criteria.search()
        })
      },
      cancel(){
        this.showModal = false
        this.$refs.chooser.model.rows=[]
        this.$refs.chooser.selectedRow={}
      },
      adjust(){   //  调整计划
        if(this.checkrows.length == 0){
          this.$showMessage('请选择用户后，再进行调整!', ['confirm'])
          return
        }
        this.showModal = true
      },
      addChecked(item) {
        console.log(item,'ces');
        if (!item.checked) {
          this.checkrows.push(item);
          console.log(this.checkrows);
        } else {
          for (let i = 0; i < this.checkrows.length; i++) {
            if (item.id == this.checkrows[i].id) {
              this.checkrows.splice(i, 1)
            }
          }
        }
      },
      search(args ){
        this.model.rows = []
        this.model.count = 0
        this.checkrows = []
        this.checkedAll = false
        this.model.search(args.condition, args.model)
      },
      delete(row){
        let gen = syncDelete(this,row)
        return co(gen)
      }
    },
    ready () {
      this.model.id = this.$login.f.id
      this.model.f_subcompany = this.$login.f.f_fengongsi
      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)
          }
        }
      }
    },
    computed: {
      selected () {
        return this.$refs.paged.$refs.grid.selected
      }
    }
  }
</script>

