<template>
  <a-modal
    :title="modalTitle"
    :width="800"
    :visible="visible"
    class="ant-modal2"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
    @ok='save'
  >
    <a-form :form="form">
      <row-list :col="1">
        <row-item v-for="(item, index) in data" :key="index">
          <a-form-item
            v-show='hiddenFlag'
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
            v-if="item.type === 5"
            :label="item.label">
            <a-input v-decorator="[item.fieldName]"/>
          </a-form-item>
          <a-form-item
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
            v-if="item.type === 1 && (item.disabledFlag === 0 || item.disabledFlag === '0')"
            :label="item.label">
            <a-input v-decorator="[item.fieldName, {initialValue: item.value, rules: [{required: item.required, message: '不能为空'}]}]"/>
          </a-form-item>
          <a-form-item
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
            v-if="item.type === 1 && (item.disabledFlag === 1 || item.disabledFlag === '1')"
            :label="item.label">
            <a-input disabled='disabled' v-decorator="[item.fieldName, {initialValue: item.value, rules: [{required: item.required, message: '不能为空'}]}]"/>
          </a-form-item>
          <a-form-item
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
            v-if="item.type === 2"
            :label="item.label">
            <a-select
              v-decorator="[item.fieldName, {initialValue: item.value, rules: [{required: item.required, message: '不能为空'}]}]"
              style="width: 120px"
            >
              <a-select-option
                v-for="option in item.optionList"
                :key="option.name"
                :label="option.name"
                :value="option.value">{{ option.name }}</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
            v-if="item.type === 3"
            :label="item.label">
            <a-date-picker
              v-decorator="[item.fieldName, {initialValue: item.value, rules: [{required: item.required, message: '不能为空'}]}]"
              style="width: 100%"
            />
          </a-form-item>
          <a-form-item
            :labelCol="BaseTool.Constant.labelCol"
            :wrapperCol="BaseTool.Constant.wrapperCol"
            v-if="item.type === 4"
            :label="item.label">
            <a-input
              style="width: 70%"
              disabled
              v-decorator="['sbName', {rules: [{required: true, message: '设备不能为空'}]}]" />
            <a-input type='hidden' v-decorator="['sbId']" />
            <a-button style="width: 30%" type="primary" @click="sbInfoHandleSelect">选择</a-button>
          </a-form-item>
        </row-item>
      </row-list>
    </a-form>
    <a-tabs v-show='isTransfer' type="card" default-active-key="1">
      <a-tab-pane key="1" tab="设备列表">
        <div class="table-operator" style="margin-bottom: 8px;">
          <a-button size="small" type="primary" @click="handleStandardSelect">
            <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="dataSource"
          :columns="columns"
          tableLayout="auto"
          rowKey="id"
          :scroll="{ x: 1600, y: BaseTool.Constant.scrollY }"
          :row-selection="rowSelection"
        >
          <span slot="action" slot-scope="record">
            <template>
              <a @click="handleView(record)">查看</a>
            </template>
          </span>
          <span slot="status" slot-scope="text">
            <badge :status="DictCache.COLOR.SB_INFO_STATUS[text]" :text="statusMap[text]" />
          </span>
        </a-table>
      </a-tab-pane>
    </a-tabs>
    <sb-info-select-modal ref="sbInfoSelectModal" @selected="sbInfoHandleSelected"/>
    <sb-info-select-modal-by-user ref="sbInfoSelectModalByUser" :type="'checkbox'" @selected="handleSbSelected"/>
  </a-modal>
</template>

<script>
import SbInfoSelectModal from '@/views/sb/info/modules/SbInfoSelectModal'
import SbInfoSelectModalByUser from '@/views/sb/info/modules/SbInfoSelectModalByFilter'
import { updateCustomFieldTemplate } from '@/api/customize/fieldTemplate'
import { addCustomFieldTemplateDataForm } from '@/api/customize/fieldTemplateData'

export default {
  name: 'SbCustomFormView',
  components: {
    SbInfoSelectModal,
    SbInfoSelectModalByUser
  },
  data () {
    return {
      confirmLoading: false,
      modalTitle: null,
      model: null,
      data: [],
      form: this.$form.createForm(this),
      visible: false,
      // 下拉框map
      typeMap: {},
      typeFieldMap: {},
      hiddenFlag: false,
      remark: null,
      isTransfer: false,
      statusMap: {},
      // 表头
      columns: [
        {
          title: '设备编号',
          dataIndex: 'no',
          width: 200
        },
        {
          title: '设备名称',
          dataIndex: 'name',
          width: 200
        },
        {
          title: '设备类型',
          dataIndex: 'type',
          width: 200,
          customRender: (text, record, index) => {
            return record.typeName
          }
        },
        {
          title: '设备等级',
          dataIndex: 'level',
          width: 200,
          customRender: (text, record, index) => {
            return this.BaseTool.Object.getField(this.levelMap, text)
          }
        },
        {
          title: '生产商',
          dataIndex: 'producerId',
          width: 200,
          customRender: (text, record, index) => {
            return record.producerName
          }
        },
        {
          title: '规格型号',
          dataIndex: 'guigeId',
          width: 200,
          customRender: (text, record, index) => {
            return record.guigeName
          }
        },
        {
          title: '状态',
          dataIndex: 'status',
          width: 200,
          scopedSlots: { customRender: 'status' }
        },
        {
          title: '操作',
          key: 'action',
          width: '200px',
          align: 'center',
          fixed: 'right',
          scopedSlots: { width: 200, customRender: 'action' }
        }
      ],
      dataSource: [],
      selectedRowKeys: [],
      selectedRows: [],
      options: {
        rowSelection: {
          selectedRowKeys: this.selectedRowKeys
        }
      }
    }
  },
  created () {
    // 下拉框map
    this.typeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.CUSTOM_FIELD_TEMPLATE_TYPE)
    this.typeFieldMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.CUSTOM_FIELD_TEMPLATE_FILED_TYPE)
    this.statusMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SB_INFO_STATUS)
  },
  methods: {
    base (data) {
      this.visible = true
      this.modalTitle = '审批单'
      this.remark = data.remark
      if (this.remark === this.DictCache.VALUE.CUSTOM_TEMPLATE_SB_REMARK.SB_ALLOCATE_FORM) {
        this.isTransfer = true
      }
      this.data = JSON.parse(data.content)
      // 调拨单处理
      if (this.data.sbInfos !== null && this.data.sbInfos !== undefined) {
        this.dataSource = JSON.parse(this.data.sbInfos)
      } else {
        this.dataSource = []
      }
    },
    handleCancel (values) {
      this.visible = false
      this.confirmLoading = false
      this.model = null
      this.data = []
      this.form.resetFields()
      this.$emit('ok', JSON.stringify(values))
    },
    handleOk (values) {
      this.visible = false
      this.confirmLoading = false
      this.model = null
      this.data = []
      this.form.resetFields()
      this.$emit('ok', JSON.stringify(values))
    },
    sbInfoHandleSelect () {
      this.$refs.sbInfoSelectModal.base({}, {})
    },
    sbInfoHandleSelected (keys, rows) {
      const [ key ] = keys
      const [ row ] = rows
      const { form: { setFieldsValue } } = this
      // 日期处理
      this.$nextTick(() => {
        setFieldsValue(Object.assign({
          'sbId': key,
          'sbNo': row.no,
          'sbName': row.name,
          'initialValue': row.initialValue,
          'currentValue': row.currentValue,
          'startDate': row.startDate,
          'workYear': row.workYear,
          'id': ''
        }))
      })
    },
    save () {
      const { form: { validateFieldsAndScroll } } = this
      this.confirmLoading = true
      validateFieldsAndScroll((errors, values) => {
        if (errors) {
          this.confirmLoading = false
          return
        }
        if (values.stopDate !== null && values.stopDate !== undefined) {
          values.stopDate = this.BaseTool.Date.formatter(values.stopDate, this.BaseTool.Date.PICKER_NORM_DATE_PATTERN)
        }
        if (this.dataSource.length > 0) { // 调拨单
          values.sbInfos = JSON.stringify(this.dataSource)
        }
        const content = JSON.stringify(values)
        const obj = {}
        obj.type = this.DictCache.VALUE.CUSTOM_TEMPLATE_SB_REMARK_NUMBER.ACTIVITY_FORM
        obj.objId = values.sbId
        obj.data = content
        obj.remark = this.remark
        // 日期处理
        if (this.BaseTool.String.isBlank(values.id)) {
          addCustomFieldTemplateDataForm(obj)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        } else {
          updateCustomFieldTemplate(values)
            .then(() => {
              this.handleCancel(values)
            }).catch(() => {
              this.confirmLoading = false
            })
        }
      })
    },
    handleStandardSelect () {
      this.$refs.sbInfoSelectModalByUser.base({ notStatusList: [this.DictCache.VALUE.SB_INFO_STATUS.IN_DIAOBO] })
    },
    handleSbSelected (keys, rows) {
      const { dataSource } = this
      const len = dataSource.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 === dataSource[j].id) {
            flag = true
          }
        }
        if (!flag) {
          dataSource.push(row)
        }
      }
    }
  }
}
</script>
