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

      <a-form-item v-show="false">
        <a-input v-decorator="['standardId']" type="hidden"/>
      </a-form-item>

      <row-list :col="2">
        <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']" />
          </a-form-item>
        </row-item>
      </row-list>
    </a-form>
    <template slot="footer">
      <a-button :loading="confirmLoading" type="primary" @click="save()">保存</a-button>
    </template>
    <part-info-select-modal ref="partInfoSelectModal" @selected="handlePartSelected"/>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { STable, Ellipsis } from '@/components'
import BaseTool from '../../../../utils/tool'
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 { generateJobByCheckStandard } from '@/api/check/checkstandard'

export default {
  name: 'BaseCheckStandard',
  components: {
    STable,
    Ellipsis,
    PartInfoSelectModal
  },
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      form: this.$form.createForm(this),
      visible: false,
      // 下拉框map
      typeMap: {},
      actionTypeMap: {},
      paramTypeMap: {},
      enableMap: {},
      periodTypeMap: {},
      checkImgList: [], // 图片
      checkFileList: [], // 文档
      defaultCheckImgList: [],
      defaultCheckFileList: [],
      uploadUrl: uploadUrl,
      userList: {},
      editingKey: '',
      headers: {
        Authorization: 'Bearer ' + Vue.ls.get(ACCESS_TOKEN)
      },
      rowSelection: {
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys
          this.selectedRows = selectedRows
        }
      },
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          customRender: (text, record, index) => {
            return index + 1
          }
        },
        {
          title: '名称',
          dataIndex: 'name',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '类型',
          dataIndex: 'type',
          scopedSlots: { customRender: 'type' }
        },
        {
          title: '上限',
          dataIndex: 'upperLimit',
          scopedSlots: { customRender: 'upperLimit' }
        },
        {
          title: '下限',
          dataIndex: 'lowerrLimit',
          scopedSlots: { customRender: 'lowerrLimit' }
        },
        {
          title: '参考值',
          dataIndex: 'referenceValue',
          scopedSlots: { customRender: 'referenceValue' }
        },
        {
          title: '正常选型',
          dataIndex: 'normalSelection',
          scopedSlots: { customRender: 'normalSelection' }
        },
        {
          title: '说明',
          dataIndex: 'instruction',
          scopedSlots: { customRender: 'instruction' }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: 150,
          scopedSlots: { customRender: 'operation' }
        }
      ],
      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, standardId) {
      this.visible = true
      // 如果是空标识添加
      if (this.BaseTool.Object.isBlank(record)) {
        this.modalTitle = '添加'
        this.data = []
        this.cacheData = []
        if (standardId != null) {
          const { form: { setFieldsValue } } = this
          // 日期处理
          this.$nextTick(() => {
            setFieldsValue({ standardId: standardId })
          })
        }
        return
      }
      this.modalTitle = '编辑'
      if (this.BaseTool.Object.isBlank(record.id)) {
        this.modalTitle = '复制'
      }
      const { form: { setFieldsValue } } = this
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign(pick(record, [
          'id'
        ])))
      })
      this.data = BaseTool.Object.copy(record.paramList)
      this.cacheData = BaseTool.Object.copy(record.paramList)
      this.editingKey = ''
    },
    save () {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        values.startTime = BaseTool.Date.formatter(values.startTime, BaseTool.Date.PICKER_NORM_DATETIME_PATTERN)
        if (this.BaseTool.String.isBlank(values.id)) {
          generateJobByCheckStandard(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          generateJobByCheckStandard(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)
      }
    },
    handleChange (value, key, column) {
      const newData = [...this.data]
      const target = newData.filter(item => key === item.id)[0]
      if (target) {
        target[column] = value
        this.data = newData
      }
    },
    edit (key) {
      const newData = [...this.data]
      const target = newData.filter(item => key === item.id)[0]
      this.editingKey = key
      if (target) {
        target.editable = true
        this.data = newData
      }
    },
    cancel (key) {
      const newData = [...this.data]
      const target = newData.filter(item => key === item.id)[0]
      this.editingKey = ''
      if (!this.checkParams(target)) {
        const data = [...this.data]
        const cacheData = [...this.cacheData]
        this.data = data.filter(item => item.id !== key)
        this.cacheData = cacheData.filter(item => item.id !== key)
        return
      }
      if (target) {
        Object.assign(target, this.cacheData.filter(item => key === item.id)[0])
        console.log(target, 'target')
        delete target.editable
        this.data = newData
      }
    },
    handleAdd () {
      if (this.editingKey !== '') {
        this.$message.error('请保存后再添加')
        return false
      }
      const { data, cacheData } = this
      console.log(this.data, this.cacheData)
      const newParam = this.getNewParam()
      const newCache = { ...newParam }
      data.push(newParam)
      cacheData.push(newCache)
    },
    handleDel () {
      const data = [...this.data]
      const cacheData = [...this.cacheData]
      this.data = data.filter(item => !this.selectedRowKeys.includes(item.id))
      this.cacheData = cacheData.filter(item => !this.selectedRowKeys.includes(item.id))
      if (this.selectedRowKeys.includes(this.editingKey)) {
        this.editingKey = ''
      }
    },
    getNewParam () {
      const newParam = {
        name: '',
        type: '1',
        upperLimit: '',
        lowerrLimit: '',
        referenceValue: '',
        normalSelection: '',
        instruction: ''
      }
      newParam.id = new Date().getTime()
      newParam.editable = true
      this.editingKey = newParam.id
      console.log(newParam, 'newparam')
      return newParam
    },
    handlePartSelect () {
      const sbId = this.form.getFieldValue('sbId')
      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
      }
    }
  }
}
</script>
