<template>
  <div class="auto select-overspread">
    <criteria-paged :model="model" v-ref:paged>
      <criteria partial='criteria' @condition-changed='$parent.selfSearch' v-ref:criteria>
        <div novalidate class="form-horizontal select-overspread container-fluid auto" partial>
          <div class="row">
            <div class="form-group col-sm-3">
              <label class="font_normal_body">客户编号</label>
              <input type="text" class="input_search" style="width:60%" v-model="model.f_userinfo_code"
                     placeholder='客户编号'
                     condition="f_userinfo_code = '{}'" @keyup.enter="search()">
            </div>
            <div class="form-group col-sm-2 button-range">
              <button class="button_search" style="margin-right: 10px" @click="search()" v-el:cba>查询</button>
              <button class="button_search" style="margin-right: 10px"  @click="$parent.$parent.createAndSend()">下发</button>
            </div>
            <div class="form-group col-sm-2 button-range">
              <button class="button_search" style="margin-right: 10px" @click="$parent.$parent.delOfCheckBook()" v-el:cba>移出</button>

            </div>
          </div>
        </div>
      </criteria>
      <data-grid :model="model" class="table_sy" partial='list' v-ref:grid>
        <template partial='head'>
          <tr>
            <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>

          </tr>
        </template>
        <template partial='body'>
          <tr>
            <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;">{{ $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">{{ row.f_address }}</td>
          </tr>
        </template>
        <template partial='foot'></template>
      </data-grid>
    </criteria-paged>
    <modal :show.sync="showCreatePlan" v-ref:modal1 :width="'50%'" :backdrop="false">
      <div slot="modal-header" class="modal-header">
        <h4 class="modal-title">
          新建计划
        </h4>
      </div>
      <div slot="modal-body" class="modal-body">
        <div class="row">
          <div class="form-group col-sm-4" >
            <label class="font_normal_body">计划名称:</label>
            <input type="text" class="input_search" v-model="createPlan.f_plan_name"
                   style="width: 60%" placeholder="请选择" />
          </div>
          <div class="form-group col-sm-4" >
            <label class="font_normal_body">计划年份:</label>
            <v-select
              class="select select_list"
              :value.sync="createPlan.f_plan_year"
              v-model="createPlan.f_plan_year"
              :search="false"
              :options='yearList'
              close-on-select
              value-single
            >
            </v-select>
          </div>
          <div class="form-group col-sm-4" >
            <label class="font_normal_body">计划月份:</label>
            <v-select
              class="select select_list"
              :value.sync="createPlan.f_plan_month"
              v-model="createPlan.f_plan_month"
              :search="false"
              :options='monthList'
              close-on-select
              value-single>
            </v-select>
          </div>
          <div class="form-group col-sm-4" >
            <label class="font_normal_body">是否共享:</label>
            <v-select
              class="select select_list"
              :search="false"
              :value.sync="createPlan.isShare"
              v-model="createPlan.isShare"
              :options='isAndNot'
              placeholder='请选择'
              close-on-select
              value-single
            >
            </v-select>
          </div>
          <div class="form-group col-sm-4" v-show="createPlan.isShare=='否'">
            <label class="font_normal_body">安&ensp;检&ensp;员:</label>
            <v-select
              class="select select_list"
              :value.sync="createPlan.checker"
              v-model="createPlan.checker"
              :options='checker'
              close-on-select
              value-single
            >
            </v-select>
          </div>
          <div class="form-group col-sm-4" >
            <label class="font_normal_body">计划开始:</label>
            <datepicker
              placeholder='请选择'
              style="width:60%"
              :disabled-days-of-week="[]"
              :format="'yyyy-MM-dd'"
              :show-rest-button="reset"
              :value.sync="createPlan.f_start_time"
              v-model="createPlan.f_start_time">
            </datepicker>
          </div>
          <div class="form-group col-sm-4" >
            <label class="font_normal_body">计划结束:</label>
            <datepicker
              placeholder='请选择'
              style="width:60%"
              :disabled-days-of-week="[]"
              :format="'yyyy-MM-dd'"
              :show-rest-button="reset"
              :value.sync="createPlan.f_end_time"
              v-model="createPlan.f_end_time">
            </datepicker>
          </div>
        </div>
      </div>
      <div slot="modal-footer" class="modal-footer" style="text-align: center">
        <button class="button_search" style="margin-right: 15px" @click="addNewPlan()">创建计划</button>
        <button class="button_search" @click="cancelCreatePlan">取消</button>
      </div>
    </modal>
  </div>
</template>

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

export default {
  title: '安检记录列表',
  props: ['row'],
  data() {
    return {
      createPlan:{
        f_safecheck_type:"年度普检",
        checker:{},
        isShare:"否",
        f_usertype:"",
        f_issued:'是',
        f_end_time:Util.toStandardDateString().replace(new Date().getFullYear().toString(),(new Date().getFullYear()+1).toString()),
        f_start_time:Util.toStandardDateString(),
        f_plan_month:(new Date().getMonth()+1).toString(),
        f_plan_year:new Date().getFullYear().toString(),
        f_plan_name:""
      },
      checker:[],
      isAndNot:[{label:'是',value:'是'},{label:'否',value:'否'}],
      yearList:[{label:"2020",value:"2020"},{label:"2021",value:"2021"},{label:"2022",value:"2022"},{label:"2023",value:"2023"},{label:"2024",value:"2024"},{label:"2025",value:"2025"},{label:"2026",value:"2026"},{label:"2027",value:"2027"},{label:"2028",value:"2028"},{label:"2029",value:"2029"},{label:"2030",value:"2030"}],
      monthList:[{label:"1",value:"1"},{label:"2",value:"2"},{label:"3",value:"3"},{label:"4",value:"4"},{label:"5",value:"5"},{label:"6",value:"6"},{label:"7",value:"7"},{label:"8",value:"8"},{label:"9",value:"9"},{label:"10",value:"10"},{label:"11",value:"11"},{label:"12",value:"12"}],
      rowdata: this.row,
      bookAll: false,
      bookList:[],
      showCreatePlan: false,
      model: new PagedList('rs/sql/safe_singleTable_OrderBy', 50,
        {
          items: '"ua.id,ua.f_address,tui.f_userinfo_code,tui.f_user_name,tui.f_user_phone,tui.f_userinfo_id"',
          tablename: '"t_user_address ua left join t_userinfo tui on ua.f_userinfo_id = tui.f_userinfo_id"',
          orderitem: '"ua.id desc"'
        }
      )
    }
  },
  ready() {
    if (this.row) {
      let condition = ''
      condition = `ua.f_check_book_id =${this.row.id}`
      this.model.search(condition)
      //只显示用户页面
      this.row.f_check_book_type = '用户'
    }
    this.searchChecker()
  },
  watch: {
    'row'(val) {
      if (val) {
        this.rowdata = val
        let condition = ''
        condition = `ua.f_check_book_id =${val.id} `
        this.model.search(condition)
      }
    }
  },
  methods: {
    async searchChecker(){
      console.log(this.$login.f.orgid)
      let res=await new HttpResetClass().load('POST', '/rs/search', {
        data:{
          source: `root.getResourceById($${this.$login.f.orgid}$,$organization$).getSpecialResByType($user$).where(row.getAttributes().get($rolestr$).indexOf($安检员$) != -1)`,
          userid: this.$login.f.id
        }
      }, {resolveMsg: null, rejectMsg: null})
      res.data.forEach((resRow) => {
        this.checker.push({label:resRow.name,value:resRow})
      })
    },
    async addNewPlan(){
      this.createPlan.f_plan_type='预约计划'
      this.createPlan.f_subcompany=this.$login.f.orgstr
      this.createPlan.f_filialeid=this.$login.f.orgid
      this.createPlan.f_create_operator=this.$login.f.name
      this.createPlan.f_create_time=Util.toStandardTimeString()
      this.createPlan.f_book_id = this.row.id
      console.log(this.createPlan)
      const addPlan = {
        f_operator:this.$login.f.name,
        f_filialeid:this.$login.f.orgid,
        f_subscribe_date:'',
        condition:this.model.condition,
        switchCheckAll:true,
        checkAll:this.bookAll,
        param:this.bookList,
        columnName: "ua.id"
      }
      if(this.createPlan.isShare=="是"){
        this.createPlan.f_checker_id=null
        this.createPlan.f_checker=null
      }else{
        this.createPlan.f_checker_id=this.createPlan.checker.id
        this.createPlan.f_checker=this.createPlan.checker.name
      }
      new HttpResetClass().load("POST",'/rs/logic/createAndAddPlan',{createPlan:this.createPlan,addPlan}).then(res=>{
        if(res.data.code==200){
          this.$showMessage("计划下发成功！"+(res.data.result.length>0?"有"+res.data.result.length+"条用户地址已经存在于其他计划中":""))
          this.cancelCreatePlan()
        }else{
          this.$showMessage("计划下发失败！")
        }
      })
    },
    createAndSend(){
      if(this.model.rows.length==0){
        Vue.showMessage("未检测到列表中有用户！")
        return
      }
      if(!this.bookAll && this.bookList.length==0){
        Vue.showMessage("请先勾选你要添入到上方计划中的用户！")
        return
      }
      this.showCreatePlan = true
    },
    cancelCreatePlan(){
      this.showCreatePlan = false
    },
    selfSearch(args) {
      if (this.rowdata.id) {
        args.condition += `and ua.f_check_book_id =${this.rowdata.id}`
        this.model.search(args.condition)
      } else {
        this.$showMessage('请选择片区')
      }
    },
    checkModel (row) {
      if (this.bookAll) {
        return true
      } else {
        return this.bookList.findIndex(res => res === row.id) !== -1;
      }
    },
    checkChange (row, e) {
      if (e.target.checked) {
        this.bookList.push(row.id)
      } else {
        this.bookList.splice(this.bookList.findIndex(res => res === row.id), 1)
      }
    },
    delOfCheckBook(){
      try {
        let condata = {
          condition :null,
          bookAll:'false'
        }
        if (this.bookAll){
          condata.bookAll = 'true'
          condata.condition = this.row.id
        }else if (this.bookList.length > 0){
          let codes = this.bookList.map( item => { return `'${item}'` } ).join()
          condata.condition = `(${codes})`
        }
        this.$showMessage('确认移出安检册', ['confirm', 'cancel']).then((res) => {
          if (res === 'confirm') {
            let http = new HttpResetClass()
            http.load('POST', 'rs/logic/CheckBookUserRemove', {data:condata},
              {resolveMsg: null, rejectMsg: '移出安检册失败'}).then(resp=>{
              this.$showMessage('移出成功')
              this.$refs.paged.$refs.criteria.search()
            }).catch(error=>{
              this.$showMessage('移出失败',error)

            })
          }
        })
      }catch (e) {
        this.$showMessage('移出失败',e)
      }
    }
  }
}
</script>
