<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="categoryMultiple" multiple @on-change="_categoryChange">
                      <input v-model="formObj.category" hidden="hidden"></input>
                      <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"
                      style="width: 100%"
                      type="date"
                      @change="_obtainSampleTime"
                    />
                  </Form-item>
                  <Form-item label="要求完成时间" prop="aeTime" class="width-32">
                    <el-date-picker
                      v-model="formObj.aeTime"
                      style="width: 100%"
                      type="datetime"
                      default-time="16:00:00"
                      @change="_askEndTime"
                    />
                  </Form-item>
                  <Form-item label="牌号" prop="name" class="width-32">
                    <Input
                      v-model="formObj.name"
                      name="name"
                      placeholder="请选择牌号"
                      @dblclick.native="_selectMaterielName"
                    />
                  </Form-item>


                  <Form-item label="卷制标准版本号" prop="unit" class="width-32">
                    <Select v-model="formObj.standard">
                      <Option v-for="item in standardList" :key="item.name" :value="item.name">
                        {{ item.name }}
                      </Option>
                    </Select>
                  </Form-item>

                  <Form-item label="机台" prop="unit" class="width-32">
                    <Select v-model="formObj.samplePoint">
                      <Option v-for="item in samplePointList" :key="item.name" :value="item.name">
                        {{ item.name }}
                      </Option>
                    </Select>
                  </Form-item>

                  <Form-item label="班次" prop="unit" class="width-32">
                    <Select v-model="formObj.classBan">
                      <Option v-for="item in classBanList" :key="item.name" :value="item.name">
                        {{ item.name }}
                      </Option>
                    </Select>
                  </Form-item>

                  <Form-item label="计量单位" prop="unit" class="width-32">
                    <!--                    <Input v-model="formObj.unit" name="unit" placeholder="计量单位" />-->
                    <Select v-model="formObj.unit">
                      <Option v-for="item in options" :key="item.name" :value="item.name">
                        {{ item.name }}
                      </Option>
                    </Select>
                  </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="flowed" class="width-32">
<!--                    <el-radio v-model="formObj.flowed" label="0" @change="show">-->
<!--                      否-->
<!--                    </el-radio>-->
<!--                    <el-radio v-model="formObj.flowed" label="1" @change="show">-->
<!--                      是-->
<!--                    </el-radio>-->

                    <el-radio-group  v-model="formObj.flowed">
                      <el-radio  :label="0">否</el-radio>
                      <el-radio :label="1">是</el-radio>
                    </el-radio-group>
                  </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" />
  </div>
</template>
<script>
/**
 * 添加编辑企业委托表
 */
import { drugSample } from '../../../api'
import UserInfo from '../../../components/user-info-single/assignPerson'
import DrugCatalogueSelect from '../../drug-register/DrugCatalogueSelect'
import SupplierSelect from '../../drug-register/SupplierSelect'
import standard from '../../../api/aptitude/standard'
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: '',
      categoryMultiple: '',
      timer: '',
      currentTime: new Date(),
      options: [
        {
          name: '支'
        },
        {
          name: '盒'
        },
        {
          name: '条'
        }
      ],
      formObj: {
        category: '',
        standard: '',
        classBan: '',
        pcTime: '',
        aeTime: '',
        pcPerson: '',
        pcPersonId: '',
        pcDepart: '',
        samplePoint: '',
        code: '',
        name: '',
        unit: '',
        spec: '',
        lotNum: '',
        quantity: '',
        flowed: 1,
        supplier: '',
        supplierId: '',
        catalogueId: '',
        remark: ''
      },
      ruleValidate: {
        declarationInspection: [
          { required: true, message: '报检单位不能为空', trigger: 'blur' }
        ],
        category: [
          { required: true, message: '价类不能为空', trigger: 'change' }
        ],
        modelSpec: [{ required: true, message: '物料编号不能为空' }],
        name: [
          { required: true, message: '物料名称不能为空', trigger: 'change' }
        ],
        obtainSampler: [
          { required: true, message: '取样人不能为空', trigger: 'change' }
        ],
        obtainSampleTime: [{ required: true, message: '取样时间不能为空' }],
        stockOrganize: [
          { required: true, message: '库存组织不能为空', trigger: 'change' }
        ]
      },
      showModal: false,
      testType: [
        {
          name: '一类'
        },
        {
          name: '二类'
        },
        {
          name: '三类'
        },
        {
          name: '四类'
        },
        {
          name: '五类'
        }
      ],
      classBanList: [
        {
          name: '甲班'
        },
        {
          name: '乙班'
        },
        {
          name: '正常班'
        }
      ],
      samplePointList: [
        {
          name: 'A1'
        },
        {
          name: 'A2'
        },
        {
          name: 'A3'
        },
        {
          name: 'A4'
        },
        {
          name: 'A5'
        },
        {
          name: 'A6'
        },
        {
          name: 'A7'
        },
        {
          name: 'B1'
        },
        {
          name: 'B2'
        },
        {
          name: 'B3'
        },
        {
          name: 'B4'
        },
        {
          name: 'B5'
        },
        {
          name: 'B6'
        },
        {
          name: 'B7'
        },
        {
          name: 'B8'
        },
        {
          name: 'B9'
        }
      ],
      standardList: [],
      footerList: [
        { id: '', name: '取消', type: '' },
        { id: '', name: '保存', type: 'primary' }
      ],
      groupData: [],
      itemIds: [],
      drugItemList: [],
      itemIdsEdit: [],
      orgList: [],
      edit: true,
      optionsTime: {
        disabledDate: function(date) {
          return date && date.valueOf() > Date.now()
        }
      }
    }
  },
  methods: {
    show() {
      console.log(this.formObj.flowed)
    },
    _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)
      }
    },
    _categoryChange(data) {
      this.formObj.category = this.categoryMultiple.join('、')
      console.log(this.formObj.category)
    },
    _open(formObj) {
      this.itemIdsEdit = []
      this.itemIds = []
      this.drugItemList = []
      this.$refs.formObj.resetFields()
      this.itemIds = []
      this.showModal = true
      this.infoVal = ['1']
      this._getStandardList({})
      this.editId = 'edit-form-product-edit'
      this._hideLoading()
      this.$refs.itemModal._init()
      this.formObj.pcTime = this.getDay(-1, '-')
      console.log('时间')
      console.log(this.formObj.pcTime)
      if (this.$string(formObj).isEmpty()) {
        this.id = ''
        this.edit = true
        this._empty()
        this.modalTitle = '添加报检信息'
      } else {
        this.id = formObj.id
        this.edit = false
        this.categoryMultiple = formObj.category.split('、')
        if (undefined === formObj.pcPerson) {
          formObj.pcPerson = ''
        }
        if (undefined === formObj.pcPersonId) {
          formObj.pcPersonId = ''
        }

        this.formObj = formObj
        if (undefined !== formObj.pcTime) {
          this.formObj.pcTime = this._dateFormat(formObj.pcTime)
        } else {
          this.formObj.pcTime = ''
        }

        if (undefined !== formObj.aeTime) {
          this.formObj.aeTime = this._dateFormat(formObj.aeTime)
        } else {
          this.formObj.aeTime = ''
        }

        console.log('this.formObj--', this.formObj)
        this.formObj.category = formObj.category
        this.modalTitle = '编辑报检信息'
        this.$refs.itemModal._getItem(formObj.id)
      }
    },
    getDay(num, str) {
      const today = new Date()
      const nowTime = today.getTime()
      const ms = 24 * 3600 * 1000 * num
      today.setTime(parseInt(nowTime + ms))
      const oYear = today.getFullYear()
      let oMoth = (today.getMonth() + 1).toString()
      if (oMoth.length <= 1) oMoth = '0' + oMoth
      let oDay = today.getDate().toString()
      if (oDay.length <= 1) oDay = '0' + oDay
      const hours =
        today.getHours() < 10 ? '0' + today.getHours() : today.getHours()
      const minutes =
        today.getMinutes() < 10 ? '0' + today.getMinutes() : today.getMinutes()
      const seconds =
        today.getSeconds() < 10 ? '0' + today.getSeconds() : today.getSeconds()
      // return oYear + str + oMoth + str + oDay + hours + minutes + seconds
      return (
        oYear +
        str +
        oMoth +
        str +
        oDay +
        ' ' +
        hours +
        ':' +
        minutes +
        ':' +
        seconds
      )
    },

    _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.formObj
          const { category, catalogueId } = this.formObj
          data.pcTime = this.formObj.pcTime
          data.aeTime = this.formObj.aeTime
          data.drugItemList = this.drugItemList
          const itemDatas = this.drugItemList
          console.log('0----0', data)
          for (let i = 0; i < itemDatas.length; i++) {
            if (undefined === itemDatas[i].name || itemDatas[i].name === '') {
              this.$Message.error('检测项目名称不能为空！')
              this._hideLoading()
              return false
            }
          }
          this._save({
            ...data,
            category,
            catalogueId
          })
        } else {
          this.$Message.error('表单验证失败')
          this._hideLoading()
        }
      })
    },
    // 添加、编辑保存
    _save: async function(data) {
      console.log('*************', data)
      // 添加
      if (this.$string(this.id).isEmpty()) {
        const result = await drugSample.addMaterialRegister(data)
        this._resultChange(result, '添加成功')
      } else {
        // 编辑
        data.id = this.formObj.id
        const result = await drugSample.editSampleVO({
          id: this.formObj.id,
          obj: data
        })
        this._resultChange(result, '编辑成功')
      }
    },

    _getStandardList: async function(data) {
      const result = await standard.list(data)
      if (result) {
        this.standardList = 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)
      console.log('时间')
      console.log(this.formObj.pcTime)
    },

    _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 = ''
      this.$refs.itemModal._init()
    },
    _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>
