<template>
  <a-modal
    :title="modalTitle"
    :width="1200"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
  >
    <a-form :form="form">

      <a-form-item v-show="false">
        <a-input v-decorator="['id']" type="hidden"/>
        <a-input v-decorator="['sbId']" type="hidden"/>
        <a-input v-decorator="['part']" 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
              disabled
              style="width: 80%"
              v-decorator="['sbNo', {rules: [{required: false, message: '请选择设备'}]}]"/>
            <a-button type="primary" style="width: 20%" @click="handleSbSelect">选择</a-button>
          </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-input
              disabled
              style="width: 80%"
              v-decorator="['partName']"/>
            <a-button type="primary" style="width: 20%" @click="handlePartSelect">选择</a-button>
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="执行人"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select v-decorator="['checkUserId']" placeholder="请选择">
              <a-select-option
                v-for="({userId, realName}) in userList"
                :key="userId"
                :label="realName"
                :value="userId">{{ realName }}
              </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-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-input
              v-decorator="['standardHours']"
              suffix="分钟"/>
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="排序"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-input-number
              :step="1"
              v-decorator="['sort', {initialValue: 1,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="['actionType', {initialValue: 1,rules: [{required: true, message: '是否启用不能为空'}]}]"
              placeholder="请选择">
              <a-select-option
                v-for="(label,value) in actionTypeMap"
                :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-select
              disabled
              v-show="false"
              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
            v-show="false"
            label="是否启用"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-select
              v-show="false"
              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="['requirement', {rules: [{required: true, message: '检查项目不能为空'}]}]"/>
          </a-form-item>
        </row-item>
        <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>
      <row-list :col="2">
        <row-item>
          <a-form-item
            label="图片"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-upload
              :action="uploadUrl"
              :multiple="true"
              list-type="picture"
              accept="image/*"
              :file-list="this.defaultCheckImgList"
              @change="handleCheckImgChange"
              :headers="headers"
            >
              <a-button> <a-icon type="upload" /> 选择上传图片 </a-button>
            </a-upload>
          </a-form-item>
        </row-item>
        <row-item>
          <a-form-item
            label="文件"
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
          >
            <a-upload
              :action="uploadUrl"
              :multiple="true"
              :file-list="this.defaultCheckFileList"
              @change="handleCheckFileChange"
              :headers="headers"
            >
              <a-button> <a-icon type="upload" /> 选择上传文件 </a-button>
            </a-upload>
          </a-form-item>
        </row-item>
      </row-list>
    </a-form>
    <title-divider title="关联备件" width="100px"></title-divider>
    <div class="table-operator">
      <a-button style="margin-left:8px;" type="primary" @click="handleSpareSelect">
        <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
      :data-source="data"
      :columns="columns"
      bordered
      ref="table"
      tableLayout="auto"
      :row-selection="rowSelection"
      rowKey="bomId">
      <template slot="num" slot-scope="text, record">
        <div class="editable-cell-input-wrapper">
          <a-input :value="text" :id="record.spareId + ',num'" @change="$event => onQuantityChange($event, record.id, 'num')" />
        </div>
      </template>
      <span slot="action" slot-scope="record">
        <template>
<!--          <a @click="handleDetailSelect(record)">修改</a>
          <a-divider type="vertical" />-->
          <a-popconfirm title="是否要删除该条数据？" @confirm="handleDelOne(record)">
            <a>删除</a>
          </a-popconfirm>
        </template>
      </span>
    </a-table>
    <template slot="footer">
      <a-button :loading="confirmLoading" type="primary" @click="save()">保存</a-button>
    </template>
    <part-info-select-modal ref="partInfoSelectModal" @selected="handlePartSelected"/>
    <sb-info-select-modal ref="sbInfoSelectModal" @selected="handleSbSelectd"/>
    <spare-part-info-select-modal-sb-info :type="'checkbox'" ref="spareSelectModal" @selected="handleSpareSelected"/>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { STable, Ellipsis } from '@/components'
import { addCheckStandard, fetchCheckStandard, updateCheckStandard } from '@/api/check/checkstandard'
import { queryUser } from '@/api/upms/user'
import { uploadUrl } from '@/api/upms/file'
import PartInfoSelectModal from '@/views/part/info/modules/PartInfoSelectModal'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import SparePartInfoSelectModalSbInfo from '@/views/sqarepartmanage/sparepartinfo/modules/SparePartInfoSelectModalSbInfo'
import SbInfoSelectModal from '@/views/sb/info/modules/SbInfoSelectModal'

export default {
  name: 'BaseCheckStandard',
  components: {
    STable,
    Ellipsis,
    SbInfoSelectModal,
    PartInfoSelectModal,
    SparePartInfoSelectModalSbInfo
  },
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      sbId: null,
      // 下拉框map
      typeMap: {},
      actionTypeMap: {},
      paramTypeMap: {},
      enableMap: {},
      periodTypeMap: {},
      checkImgList: [], // 图片
      checkFileList: [], // 文档
      defaultCheckImgList: [],
      defaultCheckFileList: [],
      userList: {},
      editingKey: '',
      uploadUrl: uploadUrl,
      headers: {
        Authorization: 'Bearer ' + Vue.ls.get(ACCESS_TOKEN)
      },
      rowSelection: {
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys
          this.selectedRows = selectedRows
        }
      },
      // 表头
      columns: [
        {
          title: '名称',
          dataIndex: 'spareName'
        },
        {
          title: '规格型号',
          dataIndex: 'ggxh'
        },
        {
          title: '数量',
          dataIndex: 'num',
          width: 150,
          scopedSlots: { customRender: 'num' }
        },
        {
          title: '操作',
          key: 'action',
          checked: true,
          align: 'center',
          // fixed: 'right',
          scopedSlots: { customRender: 'action' }
        }
      ],
      data: [],
      cacheData: [],
      selectedRowKeys: [],
      selectedRows: [],
      options: {
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys
        }
      }
    }
  },
  props: {
    /**
     * 检查类型： 1-点检 2-巡检
     */
    checkType: {
      type: Number,
      default: 1
    }
  },
  created () {
    // 下拉框map
    this.paramTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.CHECK_STANDARD_PARAM_TYPE)
    this.typeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.CHECK_STANDARD_TYPE)
    this.periodTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.CHECK_PLAN_PERIOD_TYPE)
    this.actionTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.CHECK_PLAN_ACTION_TYPE)
    this.enableMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.YES_NO)
  },
  methods: {
    base (record, sbId) {
      this.visible = true
      this.selectedRowKeys = []
      this.selectedRows = []
      this.form.resetFields()
      queryUser({}).then(res => {
        this.userList = res.data
      })
      // 如果是空标识添加
      if (this.BaseTool.Object.isBlank(record)) {
        this.modalTitle = '添加'
        this.data = []
        this.cacheData = []
        if (sbId != null) {
          this.sbId = sbId
          const { form: { setFieldsValue } } = this
          // 日期处理
          this.$nextTick(() => {
            setFieldsValue({ sbId: sbId })
          })
        }
        return
      }
      this.modalTitle = '编辑'
      if (this.BaseTool.Object.isBlank(record.id)) {
        this.modalTitle = '复制'
      }
      this.sbId = record.sbId
      // 查询列表
      fetchCheckStandard({ id: record.id }).then(res => {
        this.data = res.data.detailList
      })
      this.checkImgList = record.checkImgList
      this.checkFileList = record.checkFileList
      if (this.checkImgList == null) {
        this.defaultCheckImgList = this.BaseTool.UPLOAD.transImg(this.checkImgList)
      }
      if (this.checkImgList == null) {
        this.defaultCheckFileList = this.BaseTool.UPLOAD.transImg(this.checkFileList)
      }
      const { form: { setFieldsValue } } = this
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id',
          'sbId',
          'sbNo',
          'name',
          // 'no',
          // 'type',
          'period',
          'part',
          'partName',
          'checkUserId',
          'periodType',
          // 'actionType',
          // 'enable',
          'requirement',
          'remark'
        ])))
      })
    },
    save () {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        // 上传文件
        values.checkImgList = this.checkImgList
        values.checkFileList = this.checkFileList
        // 备件列表
        values.detailList = this.data
        if (this.BaseTool.String.isBlank(values.id)) {
          addCheckStandard(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          updateCheckStandard(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    handleCancel (values) {
      this.visible = false
      this.data = []
      this.confirmLoading = false
      this.selectedRowKeys = []
      this.selectedRows = []
      this.form.resetFields()
      if (this.BaseTool.Object.isNotBlank(values)) {
        this.$emit('ok', values)
      }
    },
    handleSbSelect () {
      this.$refs.sbInfoSelectModal.base()
    },
    handleSbSelectd (keys, rows) {
      const [ key ] = keys
      const [ row ] = rows
      const { form: { setFieldsValue } } = this
      this.sbId = key
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign({
          'sbId': key,
          'sbNo': row.no
        }))
      })
    },
    handlePartSelect () {
      const sbId = this.form.getFieldValue('sbId')
      if (this.BaseTool.Object.isBlank(sbId)) {
        this.$message.error('请先选择设备')
      }
      this.$refs.partInfoSelectModal.base({ sbId })
    },
    handlePartSelected (keys, rows) {
      const [ key ] = keys
      const [ row ] = rows
      const { form: { setFieldsValue } } = this
      this.$nextTick(() => {
        setFieldsValue(Object.assign({
          'part': key,
          'partName': row.name
        }))
      })
    },
    handleCheckImgChange (info) {
      this.defaultCheckImgList = info.fileList
      this.checkImgList = this.setFileList(info, 1)
    },
    handleCheckFileChange (info) {
      this.defaultCheckFileList = info.fileList
      this.checkFileList = this.setFileList(info, 2)
    },
    setFileList (info, type) {
      const file = info.file
      const fileList = info.fileList
      if (file.status === 'done') {
        return this.BaseTool.UPLOAD.getUploadFileDTO(fileList, type)
      } else if (file.status === 'removed') {
        return this.BaseTool.UPLOAD.getUploadFileDTO(fileList, type)
      } else if (file.status === 'error') {
        this.$message.error('上传失败')
        return null
      }
    },
    handleSpareSelect () {
      this.$refs.spareSelectModal.base(null, { sbId: this.sbId })
    },
    handleSpareSelected (record, keys, rows) {
      const addData = []
      for (let i = 0; i < rows.length; i++) {
        addData.push({ sbId: this.sbId, spareId: rows[i].id, spareName: rows[i].name, num: 1 })
      }
      const { data } = this
      for (let i = 0; i < rows.length; i++) {
        let find = false
        for (let j = 0; j < data.length; j++) {
          if (rows[i].spareId === data[j].spareId) {
            find = true
            break
          }
        }
        if (!find) {
          const selectData = {}
          selectData.spareId = rows[i].spareId
          selectData.spareName = rows[i].name
          selectData.ggxh = rows[i].ggxh
          selectData.sbId = this.sbId
          selectData.bomId = rows[i].id
          selectData.num = 1
          data.push(selectData)
        }
      }
    },
    handleDel () {
      const data = [...this.data]
      if (this.selectedRowKeys.length === 0) {
        this.$message.error('请至少选择一条数据')
        return
      }
      this.data = data.filter(item => !this.selectedRowKeys.includes(item.bomId))
    },
    handleDelOne (record) {
      const data = [...this.data]
      this.data = data.filter(item => record.bomId !== item.bomId)
    },
    onQuantityChange (e, id, attr) {
      const value = e.target.value
      console.log(value)
      if (value !== 0 && !value) {
        return
      }
      const data = [...this.data]
      const target = data.find(item => item.id === id)
      if (target) {
        target[attr] = value
        this.data = data
      }
    }
  }
}
</script>
