<template>
  <div class="flex">
    <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-4">
              <label class="font_normal_body">用户名称</label>
              <input type="text" class="input_search" style="width:60%" v-model="model.f_user_name" placeholder='用户名称'
                     condition="ui.f_user_name like '%{}%'">
            </div>
            <div class="form-group col-sm-4">
              <label class="font_normal_body">用户编号</label>
              <input type="text" class="input_search" style="width:60%" v-model="model.f_userinfo_code"
                     placeholder='用户编号' condition="ui.f_userinfo_code like '%{}%'">
            </div>
            <div class="form-group col-sm-4">
              <label class="font_normal_body">用户地址</label>
              <input type="text" class="input_search" style="width:60%" v-model="model.f_address"
                     placeholder='用户地址' condition="ua.f_address like '%{}%'">
            </div>
            <div class="form-group col-sm-4">
              <label class="font_normal_body">用户类型:</label>
              <v-select class="select select_list" :value.sync="model.f_user_type" v-model="model.f_user_type"
                        :options='$parent.$parent.userTypes' placeholder='请选择' condition="uf.f_user_type='{}'" :search="false"
                        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="model.f_user_state" v-model="model.f_user_state"
                        :options='$parent.$parent.userStates' placeholder='请选择' condition="ui.f_user_state='{}'" :search="false"
                        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="model.f_gasproperties" v-model="model.f_gasproperties"
                        :options='$parent.$parent.gasproperties' placeholder='请选择' condition="uf.f_gasproperties='{}'"
                        :search="false" 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="model.f_startfile_time" v-model="model.f_startfile_time"
                          condition="ui.f_createfile_date >= '{} 00:00:00'">
              </datepicker>
            </div>
            <div class="form-group col-sm-4">
              <label class="font_normal_body">开户截止:</label>
              <datepicker placeholder='请选择' :disabled-days-of-week="[]" style="width:60%" :format="'yyyy-MM-dd'"
                          :show-rest-button="reset" :value.sync="model.f_endfile_time" v-model="model.f_endfile_time"
                          condition="ui.f_createfile_date <= '{} 23:59:59'">
              </datepicker>
            </div>
            <div class="form-group col-sm-4">
              <label class="font_normal_body">派发情况:</label>
              <v-select class="select select_list" :value.sync="model.yearCheck" v-model="model.yearCheck"
                        :options='$parent.$parent.yearCheckList' placeholder='请选择' condition="{}" :search="false"
                        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="model.f_start_time" v-model="model.f_start_time">
              </datepicker>
            </div>
            <div class="form-group col-sm-4">
              <label class="font_normal_body">安检截止:</label>
              <datepicker placeholder='请选择' :disabled-days-of-week="[]" style="width:60%" :format="'yyyy-MM-dd'"
                          :show-rest-button="reset" :value.sync="model.f_end_time" v-model="model.f_end_time">
              </datepicker>
            </div>
            <div class="form-group col-sm-4">
              <label class="font_normal_body">安检状态:</label>
              <v-select class="select select_list" :value.sync="model.f_last_check_state"
                        v-model="model.f_last_check_state" :options='$parent.$parent.entry_status' placeholder='请选择'
                        :search="false" close-on-select value-single>
              </v-select>
            </div>
            <div class="form-group col-sm-4">
              <label class="font_normal_body">安检时间:</label>
              <input type="number" class="input_search" v-model="model.month" style="width: 60%"
                     placeholder="距上次安检时间(月)" condition="DATEDIFF(MONTH, ui.f_last_check_date, GETDATE()) > {}">
            </div>
            <div class="form-group col-sm-4">
              <label class="font_normal_body">入户次数</label>
              <input type="text" class="input_search" style="width:60%" v-model="model.f_num"
                     placeholder='入户次数'>
            </div>
          </div>
          <div class="row">
            <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.showCreateCheckPlan()"
                      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" onClick="event.cancelBubble = true" :checked="$parent.$parent.$parent.checkAll"
                       @change="$parent.$parent.$parent.setCheckAll()" /> 全选
              </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>
          </tr>
        </template>
        <template partial='body'>
          <tr>
            <td style="text-align: center;white-space:nowrap;">
              <input v-if="!row.f_plan_id" 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"><span>{{ row.f_userinfo_code }}</span></td>
            <td style="text-align:center"><span>{{ row.f_user_name }}</span></td>
            <td style="text-align:center"><span>{{ row.f_user_type }}</span></td>
            <td style="text-align:center"><span>{{ row.f_user_phone }}</span></td>
            <td style="text-align:center"><span>{{ row.f_meter_classify }}</span></td>
            <td style="text-align:center"><span>{{ row.f_last_check_date }}</span></td>
            <td style="text-align:center"><span>{{ row.f_address }}</span></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' placeholder='请选择' 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' placeholder='请选择' 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' placeholder='请选择' 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_safecheck_type"
                      v-model="createPlan.f_safecheck_type" :search="false" :options='ntoway' 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.checkers"
              v-model="createPlan.checkers"
              :options='checker'
              placeholder='请选择'
              :multiple="true"
            >
            </v-select>
          </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="cancel">取消</button>
      </div>
    </modal>
    <work-busy :is-busy="isBusy"></work-busy>

  </div>
</template>

<script>
import { HttpResetClass, PagedList } from 'vue-client'
import Vue from "vue";
import * as Util from "./../Util";
export default {
  title: '安检情况明细',
  data() {
    return {
      checkAll: false,
      searchCondition: '',
      isBusy:false,
      createPlan: {
        f_plan_name: '',
        f_plan_year: '',
        checkers: [],
        f_plan_month: '',
        f_checkerstr: '',
        isShare: '否',
        f_issued: '否',
        f_checker_id: null,
        checker: {},
        f_checker: null,
        f_safecheck_type: '',
      },
      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 }],
      isAndNot: [{ label: '是', value: '是' }, { label: '否', value: '否' }],
      checker: [],
      checkes: [],
      showCreatePlan: false,
      entry_status: this.$appdata.getParam('安检状态') ? [{ label: '全部', value: '' }, ...this.$appdata.getParam('安检状态')] : [{ label: '全部', value: '' }],
      yearCheckList: [{ label: "全部", value: "" }, { label: "已在计划中", value: "ua.f_plan_id is not null" }, { label: "未在计划中", value: "ua.f_plan_id is null" }],
      gasproperties: this.$appdata.getParam('用气性质') ? [{ label: '全部', value: '' }, ...this.$appdata.getParam('用气性质')] : [{ label: '全部', value: '' }],
      userStates: this.$appdata.getParam('安检用户状态') ? [{ label: '全部', value: '' }, ...this.$appdata.getParam('安检用户状态')] : [{ label: '全部', value: '' }],
      userTypes: this.$appdata.getParam('用户类型') ? [{ label: '全部', value: '' }, ...this.$appdata.getParam('用户类型')] : [{ label: '全部', value: '' }],
      model: new PagedList('rs/sql/FetchUserFileByOrgNoRuHuSXQ', 50, {
        "orderitem": "'f_residential_area,f_building,f_unit,f_floor,f_room'",
        "f_usertype": "''",
        "month": "''",
        "SafeCheckSX": {"f_check_start": '', "f_check_end": ''},
        "SafeCheckCQ": "''",
        "startday":"''",
        "endday":"''"}),
    }
  },
  props: ['checkrow'],
  async ready() {
    this.search()
    await this.searchChecker()
  },
  computed: {
    ntoway() {
      return this.$appdata.getParam('安检类型')
    }
  },
  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)
      }
    },
    async searchChecker() {
      let res = await new HttpResetClass().load('POST', '/rs/search', {
        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 })
      let arr = []
      res.data.forEach((resRow) => {
        if (!arr.includes(resRow.name) && resRow.state == '在职') {
          arr.push(resRow.name)
          this.checker.push({ label: resRow.name, value: resRow })
        }
      })
    },
    setCheckAll() {
      this.checkAll = !this.checkAll
      this.checkes = []
    },
    showCreateCheckPlan() {
      if (this.model.rows.length == 0) {
        Vue.showMessage("未检测到列表中有用户！")
        return
      }
      if (!this.checkAll && this.checkes.length == 0) {
        Vue.showMessage("请先勾选用户！")
        return
      }
      this.createPlan.f_plan_name = this.checkrow.f_residential_area
      this.showCreatePlan = true
    },
    validationCreatePlan() {
      if (!this.createPlan.f_plan_name) {
        Vue.showMessage("请输入安检计划名称！")
        return false
      }
      if (!this.createPlan.f_plan_year) {
        Vue.showMessage("请选择安检年份！")
        return false
      }
      if (!this.createPlan.f_plan_month) {
        Vue.showMessage("请选择安检月份！")
        return false
      }
      if (this.createPlan.isShare == "否") {
        if (JSON.stringify(this.createPlan.checker) == '{}') {
          Vue.showMessage("请选择安检人员！")
          return false
        }
      } else {
        this.createPlan.f_checker = ''
      }
      if (!this.createPlan.f_safecheck_type) {
        Vue.showMessage("请选择安检类型！")
        return false
      }
      return true
    },
    async addNewPlan() {
      if (!this.validationCreatePlan()) {
        return
      }
      this.isBusy = true
      let res = await new HttpResetClass().load("POST", "/rs/sql/getCheckplan", { data: { condition: "f_plan_name='" + this.createPlan.f_plan_name + "'", sortfield: 'f_create_time desc' } })
      if (res.data.length > 0) {
        Vue.showMessage("计划名称不能重复！")
        this.isBusy = false
        return
      }
      if (this.createPlan.isShare == "是") {
        if (this.createPlan.checkers.length > 0) {
          this.createPlan.f_checkerstr = this.createPlan.checkers.map(value => value.name).join(',').trim()
        }
        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
      }
      this.createPlan.f_plan_type = '预约计划'
      this.createPlan.f_subcompany = this.$login.f.orgs
      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.checkAll = this.checkAll
      this.createPlan.searchCondition = this.searchCondition
      this.createPlan.checkes = this.checkes.join()

      new HttpResetClass().load('POST', "/rs/logic/createCheckPlanAndAddPlanItem", {
        data: this.createPlan
      }, { resolveMsg: '新建计划成功！', rejectMsg: '新建计划失败！' })
        .then(() => {
          this.checkAll = false
          this.checkes = []
          this.showCreatePlan = false
          this.$showMessage('创建计划成功')
          this.isBusy = false
        }).catch(() => {
          this.checkAll = false
          this.checkes = []
          this.showCreatePlan = false
          this.$showMessage('创建计划失败')
          this.isBusy = false
      })
      this.createPlan = {
        f_plan_name: '',
        f_plan_year: '',
        f_plan_month: '',
        isShare: '否',
        f_issued: '否',
        f_checker_id: null,
        checker: {},
        checkers: [],
        f_checker: null,
        f_checkerstr: '',
        f_safecheck_type: '',
        f_create_operator: ''
      }
    },
    cancel() {
      this.showCreatePlan = false
      this.checkes = []
      this.createPlan = {
        f_plan_name: '',
        f_plan_year: '',
        f_plan_month: '',
        isShare: '否',
        f_issued: '否',
        f_checker_id: null,
        checker: {},
        f_checker: null,
        f_safecheck_type: '',
      }
    },
    search() {
      this.$refs.paged.$refs.criteria.search()
    },
    async selfSearch(args) {
      if (!this.checkrow) {
        return
      }
      if (args.model.f_num) {
        if (args.model.f_num == '0'){
          args.condition += ` and f_num is null`
        }else {
          args.condition += ` and f_num = '${args.model.f_num}'`
        }
      }
      if (args.model.f_last_check_state == '未检') {
        let nocheckcon = 'and ( ui.f_last_check_date is null '
        if(args.model.f_start_time){
          nocheckcon += ` or ui.f_last_check_date <='${args.model.f_start_time} 00:00:00' `
        }
        if(args.model.f_end_time){
          nocheckcon += ` or ui.f_last_check_date >='${args.model.f_end_time} 23:59:59' `
        }
        nocheckcon += ')'
        args.condition +=  nocheckcon
      }else{
        if(args.model.f_last_check_state){
          args.condition += ` and ui.f_last_check_state  = '${args.model.f_last_check_state}'`
        }
        if(args.model.f_start_time){
          args.condition += ` and ui.f_last_check_date >='${args.model.f_start_time} 00:00:00' `
        }
        if(args.model.f_end_time){
          args.condition += ` and ui.f_last_check_date <='${args.model.f_end_time} 23:59:59' `
        }
      }
      let condition = ''
      condition = args.condition += ` and area.f_residential_area = '${this.checkrow.f_residential_area}' and ui.f_orgid = '${this.$login.f.orgid}'`
      this.searchCondition = condition
      this.model.search(condition)
    },
  },
  watch: {
    'checkrow'() {
      this.search()
    }
  }
}
</script>
