<template>
  <a-modal
    :title="modalTitle"
    :width="1000"
    :visible="visible"
    :confirmLoading="confirmLoading"
    class="ant-modal2"
    @cancel="handleCancel"
  >
    <a-form :form="form">

      <a-form-item v-show="false">
        <a-input v-decorator="['id']" type="hidden"/>
      </a-form-item>
      <row-list :col="2">
        <row-item>
          <a-form-item
            label="编码"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              disabled
              v-decorator="['no', {rules: [{required: false, message: '编码不能为空'}]}]"/>
          </a-form-item>
        </row-item>
        <row-item>

          <a-form-item
            label="计划名称"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              v-decorator="['name', {rules: [{required: true, message: '计划名称不能为空'}]}]"/>
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="负责人方式"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select
              v-decorator="['checkUserType', {rules: [{required: true, message: '负责人方式不能为空'}]}]"
              placeholder="请选择">
              <a-select-option
                v-for="(label,value) in checkUserTypeMap"
                :key="value"
                :label="label"
                :value="parseInt(value)">{{ label }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </row-item>

        <row-item>
          <a-form-item
            label="负责人"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              disabled
              style="width: 80%"
              v-decorator="['checkUserName']"/>
            <a-button type="primary" style="width: 20%" @click="handleUserSelect">选择</a-button>
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="负责人id"

            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input
              disabled
              v-decorator="['checkUserId']"/>
          </a-form-item>
        </row-item>
        <!-- <row-item>
          <a-form-item
            label="计划周期"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
            style="margin-bottom:0;"
          >

            <a-input-number
              v-show="false"
              v-decorator="['require1', {initialValue: 111, rules: [{required: true}]}]" />
            <a-form-item :style="{ display: 'inline-block', width: '70%' }">
              <a-input-number
                style="width: 100%"
                :min="1"
                v-decorator="['period', {initialValue: 1,rules: [{required: true, message: '计划周期不能为空'}]}]"/>
            </a-form-item>
            <a-form-item
              :style="{ display: 'inline-block', width: '30%' }"
            >
              <a-select
                v-decorator="['periodType', {initialValue: 1,rules: [{required: true, message: '周期类型不能为空'}]}]"
                placeholder="请选择">
                <a-select-option
                  v-for="(label,value) in periodTypeMap"
                  :key="value"
                  :label="label"
                  :value="parseInt(value)">{{ label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-form-item>
        </row-item>-->
        <row-item>
          <a-form-item
            label="检查类型"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select
              disabled
              v-decorator="['type', {initialValue:checkType,rules: [{required: true, message: '检查类型不能为空'}]}]"
              placeholder="请选择">
              <a-select-option
                v-for="(label,value) in typeMap"
                :key="value"
                :label="label"
                :value="parseInt(value)">{{ label }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="有效时间"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
            style="margin-bottom:0;"
          >
            <!-- 解决校验问题 -->
            <a-input-number
              v-show="false"
              v-decorator="['require2', {initialValue: 111, rules: [{required: true}]}]" />
            <a-form-item :style="{ display: 'inline-block', width: '70%' }">
              <a-input-number
                style="width: 100%"
                :min="1"
                v-decorator="['validTime', {initialValue: 1,rules: [{required: true, message: '有效时间不能为空'}]}]"/>
            </a-form-item>
            <a-form-item :style="{ display: 'inline-block', width: '30%' }">
              <a-select
                v-decorator="['validTimeType', {initialValue: 1,rules: [{required: true, message: '有效时间类型不能为空'}]}]"
                placeholder="请选择">
                <a-select-option
                  v-for="(label,value) in validTimeTypeMap"
                  :key="value"
                  :label="label"
                  :value="parseInt(value)">{{ label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-form-item>
        </row-item>
        <row-item>

          <a-form-item
            label="计划开始时间"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-date-picker
              style="width: 100%"
              :format="BaseTool.Date.PICKER_NORM_DATE_PATTERN"
              v-decorator="['startTime', {rules: [{required: true, message: '计划开始时间不能为空'}]}]"/>
          </a-form-item>
        </row-item>
        <row-item>

          <a-form-item
            label="计划结束时间"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-date-picker
              style="width: 100%"
              :format="BaseTool.Date.PICKER_NORM_DATE_PATTERN"
              v-decorator="['endTime', {rules: [{required: true, message: '计划结束时间不能为空'}]}]"/>
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="是否启用"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select
              v-decorator="['enable', {initialValue:1,rules: [{required: true, message: '是否启用不能为空'}]}]"
              placeholder="请选择">
              <a-select-option
                v-for="(label,value) in enableMap"
                :key="value"
                :label="label"
                :value="parseInt(value)">{{ label }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </row-item>
      </row-list>
      <row-list :col="1">
        <row-item>
          <a-form-item
            label="备注"
            :labelCol="BaseTool.Constant.labelCol2"
            :wrapperCol="BaseTool.Constant.wrapperCol2"
          >
            <a-textarea
              :rows="4"
              v-decorator="['remark', {rules: [{required: false, message: '备注不能为空'}]}]"/>
          </a-form-item>
        </row-item>
      </row-list>
    </a-form>
    <a-tabs type="card" default-active-key="1">
      <a-tab-pane key="1" tab="计划设备">
        <div class="table-operator">
          <a-button size="small" type="primary" @click="handleProjectSelect">
            <a-icon type="plus"/>
            添加
          </a-button>
          <a-button class="margin-left8" size="small" type="danger" @click="handleDel">
            <a-icon type="delete"/>
            删除
          </a-button>
        </div>
        <a-table
          bordered
          :data-source="data"
          :columns="columns"
          tableLayout="auto"
          rowKey="id"
          :row-selection="rowSelection">

        </a-table>
      </a-tab-pane>
    </a-tabs>
    <check-project-select-modal :check-type="checkType" :type="'checkbox'" ref="projectSelectModal" @selected="handleProjectSelected"/>
    <user-select-modal ref="userSelectModal" @selected="handleUserSelected"/>
    <template slot="footer">
      <a-button :loading="confirmLoading" type="primary" @click="save()">保存</a-button>
    </template>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { addCheckPlan, updateCheckPlan } from '@/api/check/checkplan'
import CheckProjectSelectModal from '@/views/check/checkproject/modules/CheckProjectSelectModal'
import UserSelectModal from '@/views/upms/user/modules/UserSelectModal'

export default {
  name: 'BaseCheckPlan',
  components: {
    CheckProjectSelectModal,
    UserSelectModal
  },
  props: {
    /**
     * 检查类型： 1-点检 2-巡检
     */
    checkType: {
      type: Number,
      default: 1
    }
  },
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      // 下拉框map
      typeMap: {},
      periodTypeMap: {},
      checkUserTypeMap: {},
      validTimeTypeMap: {},
      enableMap: {},
      rowSelection: {
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys
          this.selectedRows = selectedRows
        }
      },
      // 表头
      columns: [
        {
          title: '项目名称',
          dataIndex: 'name'
        }
      ],
      data: [],
      selectedRowKeys: [],
      selectedRows: [],
      options: {
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys
        }
      }

    }
  },
  created () {
    // 下拉框map
    this.typeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.CHECK_STANDARD_TYPE)
    this.checkUserTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.CHECK_USER_TYPE)
    this.periodTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.CHECK_PLAN_PERIOD_TYPE)
    this.validTimeTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.CHECK_PLAN_PERIOD_TYPE)
    this.enableMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.YES_NO)
  },
  methods: {
    base (record) {
      this.visible = true
      // 如果是空标识添加
      if (this.BaseTool.Object.isBlank(record)) {
        this.modalTitle = '添加'
        this.data = []
        return
      }
      this.modalTitle = '编辑'
      const { form: { setFieldsValue } } = this
      // 日期处理
      record.startTime = this.BaseTool.Moment(record.startTime, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
      record.endTime = this.BaseTool.Moment(record.endTime, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
      record.lastGeneratedTime = this.BaseTool.Moment(record.lastGeneratedTime, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'no',
          'name',
          'checkUserType',
          'checkUserId',
          'checkUserName',
          'period',
          'type',
          'periodType',
          'validTime',
          'validTimeType',
          'startTime',
          'endTime',
          'enable',
          'remark'
        ])))
      })
      this.data = record.projectList !== null ? record.projectList : []
    },
    save () {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        //
        if (this.data.length === 0) {
          this.$message.error('请添加计划设备')
          this.confirmLoading = false
          return
        }
        values.projectList = this.data
        // 日期处理
        values.startTime = this.BaseTool.Date.formatter(values.startTime, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        values.endTime = this.BaseTool.Date.formatter(values.endTime, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        values.lastGeneratedTime = this.BaseTool.Date.formatter(values.lastGeneratedTime, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        if (this.BaseTool.String.isBlank(values.id)) {
          addCheckPlan(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          updateCheckPlan(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      this.form.resetFields()
      if (this.BaseTool.Object.isNotBlank(values)) {
        this.$emit('ok', values)
      }
    },
    handleProjectSelect () {
      this.$refs.projectSelectModal.base()
    },
    handleProjectSelected (record, keys, rows) {
      const { data } = this
      const len = data.length
      for (let i = 0; i < rows.length; i++) {
        const row = rows[i]
        let flag = false
        for (let j = 0; j < len; j++) {
          if (row.id === data[j].id) {
            flag = true
          }
        }
        if (!flag) {
          data.push(row)
        }
      }
    },
    handleUserSelect () {
      this.$refs.userSelectModal.base()
    },
    handleUserSelected (selectedRowKeys, selectedRow) {
      const { form: { setFieldsValue } } = this
      const [ key ] = selectedRowKeys
      const [ row ] = selectedRow
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign({
          'checkUserId': row.userId,
          'checkUserName': row.realName
        }))
        this.showPart = true
      })
    },
    handleDel () {
      const data = [...this.data]
      if (this.selectedRowKeys.length === 0) {
        this.$message.error('请至少选择一条数据')
        return
      }
      this.data = data.filter(item => !this.selectedRowKeys.includes(item.id))
    }

  }
}
</script>
