<template>
  <div>
    <Modal v-model="showModal" v-drag :mask-closable="false" width="1200" :styles="{marginTop:'-90px'}">
      <p slot="header">
        {{ modalTitle }}
      </p>
      <div>
        <Form
          :id="editId"
          ref="formObj"
          :model="formObj"
          :rules="ruleValidate"
          :label-width="95"
          inline
        >
          <div>
            <Collapse v-model="infoVal" class="coll-edit coll-search">
              <Panel name="1">
                报检信息
                <p slot="content">

                  <Form-item label="业务类型" prop="category" class="width-32">
                    <Select v-model="formObj.category">
                      <Option v-for="item in testType" :key="item.name" :value="item.name">
                        {{ item.name }}
                      </Option>
                    </Select>
                  </Form-item>
                  <Form-item label="请检时间" prop="pcTime" class="width-32">
                    <el-date-picker
                      v-model="formObj.pcTime"
                      type="datetime"
                      placeholder="请选择请检时间"
                      default-time="12:00:00"
                      @change="_obtainSampleTime"
                    />
                  </Form-item>
                  <Form-item label="要求完成时间" prop="aeTime" class="width-32">
                    <el-date-picker
                      v-model="formObj.aeTime"
                      type="datetime"
                      placeholder="请选择要求完成时间"
                      default-time="16:00:00"
                      @change="_askEndTime"
                    />
                  </Form-item>
                  <Form-item label="请检人" prop="pcPerson" class="width-32">
                    <Input v-model="formObj.pcPerson" name="pcPerson" readonly  @click.native="_selectSamplingPerson"/>
                  </Form-item>
                  <Form-item label="请检部门" prop="pcDepart" class="width-32">
                    <Input v-model="formObj.pcDepart" name="pcDepart" placeholder="请检部门"/>
                  </Form-item>
                  <Form-item label="采样点" prop="samplePoint" class="width-32">
                    <Input v-model="formObj.samplePoint" name="samplePoint" placeholder="采样点" />
                  </Form-item>
                  <Form-item label="物品名称" prop="name" class="width-32">
                    <Input
                      v-model="formObj.name"
                      name="name"
                      readonly
                      placeholder="请选择物品名称"
                      @click.native="_selectMaterielName"
                    />
                  </Form-item>
                  <Form-item label="物品编码" prop="code" class="width-32">
                    <Input v-model="formObj.code" name="code" placeholder="选择物品名称后自动生成" readonly />
                  </Form-item>

                  <Form-item label="计量单位" prop="unit" class="width-32">
                    <Input v-model="formObj.unit" name="unit" placeholder="计量单位"  />
                  </Form-item>

                  <Form-item label="规格" prop="spec" class="width-32">
                    <Input v-model="formObj.spec" name="spec" placeholder="规格"  />
                  </Form-item>

                  <Form-item label="批号" prop="lotNum" class="width-32">
                    <Input v-model="formObj.lotNum" name="lotNum" placeholder="批号"  />
                  </Form-item>
                  <Form-item label="数量" prop="quantity" class="width-32">
                    <Input v-model="formObj.quantity" name="quantity" placeholder="数量"  />
                  </Form-item>
                  <Form-item label="供应商" prop="supplier" class="width-32">
                    <Input v-model="formObj.supplier" name="supplier"  placeholder="选择物料名称后自动生成">
                      <Icon slot="suffix" type="md-add-circle" @click="_selectSupply"/>
                    </Input>
                  </Form-item>
                  <Form-item label="备注" prop="remark" style="width:96.8%;margin-bottom: 10px !important;">
                    <Input v-model="formObj.remark" placeholder="请输入备注" type="textarea" :rows="2" name="remark" />
                  </Form-item>
                  <Alert type="success" style="text-align: center;font-size: 15px;margin: 5px">
                    检测项目列表
                  </Alert>
                  <SampleItemList ref="itemModal" @on-result-change="_testResult" />
                </p>
              </Panel>
            </Collapse>
          </div>
        </Form>
      </div>
      <div slot="footer">
        <modal-footer ref="footerModal" :footer="footerList" @on-result-change="_footerResult" />
      </div>
    </Modal>

    <!--选择人员-->
    <UserInfo ref="userModal" is-change @on-result-change="_userData" />
    <!--选择物料-->
    <DrugCatalogueSelect ref="materialModal" is-change @on-result-change="_backMaterielNameData" />
    <!--供应商-->
    <SupplierSelect ref="supplyModal" @on-result-change="_resultModal"></SupplierSelect>
  </div>
</template>
<script>
/**
 * 添加编辑企业委托表
 */
import UserInfo from '../../../components/user-info-single/assignPerson'
import { drugSample } from '../../../api'
import DrugCatalogueSelect from '../../drug-register/DrugCatalogueSelect'
import SupplierSelect from '../../drug-register/SupplierSelect'
import SampleItemList from './sample-manage/SampleItemList'
export default {
  components: {
    SampleItemList,
    DrugCatalogueSelect,
    SupplierSelect,
    UserInfo
  },
  data() {
    // const validateNumber = function(rule, value, callback) {
    //   if (!value) {
    //     return callback(new Error('样本编号不能为空!'))
    //   } else if (!/^[^\u4e00-\u9fa5]+$/.test(value)) {
    //     return callback(new Error('不能包含中文!'))
    //   } else {
    //     callback()
    //   }
    // }
    return {
      editId: 'edit-form',
      infoVal: ['1'], // 默认展开第一个
      id: '',
      modalTitle: '',
      formObj: {
        declarationInspection: '鲁丽钢铁',
        category: '',
        pcTime: '',
        aeTime: '',
        pcPerson: '',
        pcPersonId: '',
        pcDepart: '',
        samplePoint: '',
        code: '',
        name: '',
        unit: '',
        spec: '',
        lotNum: '',
        quantity: '',
        supplier: '',
        supplierId: '',
        catalogueId: '',
        remark: ''
      },
      ruleValidate: {
        category: [
          { required: true, message: '检测类型不能为空', trigger: 'change' }
        ],
        code: [{ required: true, message: '物料编号不能为空' }],
        name: [
          { required: true, message: '物料名称不能为空', trigger: 'change' }
        ],
        supplier: [
          { required: true, message: '供应商不能为空', trigger: 'change' }
        ]
      },
      showModal: false,
      testType: [
        {
          name: '来料检测'
        }
      ],
      footerList: [
        { id: '', name: '取消', type: '' },
        { id: '', name: '保存', type: 'primary' }
      ],
      groupData: [],
      drugItemList: [],
      itemIds: [],
      itemIdsEdit: [],
      orgList: [],
      edit: true,
      optionsTime: {
        disabledDate: function(date) {
          return date && date.valueOf() > Date.now()
        }
      }
    }
  },
  methods: {
    _testResult(data) {
      this.drugItemList = data
      this.itemIds = []
      // 编辑和添加不一样，添加只是新增刚添加的检测项目
      if (this.edit) {
        for (let i = 0; i < data.length; i++) {
          if (data[i].aptitudeId !== undefined) {
            this.itemIds.push(data[i].aptitudeId)
          }
        }
      } else {
        for (let i = 0; i < data.length; i++) {
          if (data[i].aptitudeId !== undefined) {
            this.itemIds.push(data[i].aptitudeId)
          }
        }
      }
      this.itemIdsEdit = []
      for (let i = 0; i < data.length; i++) {
        this.itemIdsEdit.push(data[i].aptitudeId)
      }
    },
    _open(formObj) {
      this.$refs.formObj.resetFields()
      this.itemIds = []
      this.showModal = true
      this.infoVal = ['1']
      this.editId = 'edit-form-quzhiyang-qita'
      this._hideLoading()
      this.$refs.itemModal._init()
      if (this.$string(formObj).isEmpty()) {
        this.id = ''
        this.edit = true
        this._empty()
        this.modalTitle = '添加报检信息'
      } else {
        this.id = formObj.id
        this.edit = false
        // if (undefined === formObj.obtainSampler) {
        //   formObj.obtainSampler = ''
        // }
        if (undefined !== formObj.pcTime) {
          formObj.pcTime = this._dateFormat(formObj.pcTime)
        }
        if (undefined !== formObj.aeTime) {
          formObj.aeTime = this._dateFormat(formObj.aeTime)
        }
        this.formObj = formObj
        console.log('this.formObj--', this.formObj)
        this.formObj.category = formObj.category
        this.modalTitle = '编辑报检信息'
        this.$refs.itemModal._getItem(formObj.id)
      }
    },
    _selectMaterielName() {
      this.$refs.materialModal._open()
    },
    _trim(str) {
      return str ? str.replace(/(^\s*)|(\s*$)/g, '') : ''
    },
    // 返回样品信息
    _backMaterielNameData(data) {
      this.formObj.name = data.name
      this.formObj.spec = data.spec
      this.formObj.code = data.code
      this.formObj.catalogueId = data.id
      this.$refs.itemModal._open(data.id)
    },
    _ok(msg) {
      this.$refs.formObj.validate(valid => {
        if (valid) {
          const data = this.$serialize(this.editId)
          const { category, catalogueId, supplierId } = this.formObj
          data.pcTime = this.formObj.pcTime
          data.aeTime = this.formObj.aeTime
          data.itemIds = this.itemIds
          data.drugItemList = this.drugItemList
          this._save({
            ...data,
            category,
            catalogueId,
            supplierId
          })
        } else {
          this.$Message.error('表单验证失败')
          this._hideLoading()
        }
      })
    },
    // 添加、编辑保存
    _save: async function(data) {
      // 添加
      if (this.$string(this.id).isEmpty()) {
        const result = await drugSample.addMaterialRegister(data)
        this._resultChange(result, '添加成功')
      } else {
        // 编辑
        data.itemIds = this.itemIdsEdit.join(',')
        const result = await drugSample.edit({
          id: this.formObj.id,
          obj: data
        })
        this._resultChange(result, '编辑成功')
      }
    },

    _dateFormat: function(time) {
      const date = new Date(time)
      const year = date.getFullYear()
      /* 在日期格式中，月份是从0开始的，因此要加0
           * 使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
           * */
      const month =
        date.getMonth() + 1 < 10
          ? '0' + (date.getMonth() + 1)
          : date.getMonth() + 1
      const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
      const hours =
        date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
      const minutes =
        date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
      const seconds =
        date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
      // 拼接
      return (
        year +
        '-' +
        month +
        '-' +
        day +
        ' ' +
        hours +
        ':' +
        minutes +
        ':' +
        seconds
      )
    },
    // 请检时间
    _obtainSampleTime(data) {
      this.formObj.pcTime = this._dateFormat(data)
    },

    _askEndTime(data) {
      this.formObj.aeTime = this._dateFormat(data)
    },

    // 清空数据
    _empty() {
      this.formObj.declarationInspection = '鲁丽钢铁'
      this.formObj.category = ''
      this.formObj.sampleCode = ''
      this.formObj.name = ''
      this.formObj.modelSpec = ''
      this.formObj.sampleId = ''
      this.formObj.supplier = ''
      this.formObj.supplierId = ''
      this.formObj.obtainSampler = ''
      this.formObj.obtainSamplerId = ''
      this.formObj.remark = ''
    },
    _footerResult(name) {
      switch (name) {
        case '取消':
          this._cancel()
          break
        case '保存':
          this._ok()
          break
      }
    },
    _hideLoading() {
      this.$refs.footerModal._hideLoading()
    },
    _resultChange(result, msg) {
      if (result) {
        this.showModal = false
        this.$Message.success(msg)
        this.$emit('on-result-change')
      }
      this._hideLoading()
    },
    _cancel() {
      this.showModal = false
      this.itemIds = []
      this.itemIdsEdit = []
      this.formObj.sampleId = ''
    },
    _selectSamplingPerson() {
      this.$refs.userModal._open('pcPerson')
    },
    _userData(data, msg) {
      // 选择人员返回数据
      if (msg === 'pcPerson') {
        // 选择取样人取样人
        this.formObj.pcPerson = data.realname
        this.formObj.pcPersonId = data.userId
      }
    },
    // 选择供应商
    _selectSupply() {
      if (!this.edit) return
      this.$refs.supplyModal._open()
    },
    //  回调供应商
    _resultModal(data) {
      this.formObj.supplierId = data.id
      this.formObj.supplier = this._trim(data.name)
    }
  }
}
</script>
<style>
.width-32 {
  width: 32%;
}
</style>
