<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="declarationInspection" class="width-32">
                    <Input v-model="formObj.pcPerson" name="declarationInspection" />
                  </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="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 { drugSample } from '../../../api'
import SupplierSelect from '../../drug-register/SupplierSelect'
import DrugCatalogueSelect from './DrugCatalogueSelect'
import SampleItemList from './sample-manage/SampleItemList'
export default {
  components: {
    SampleItemList,
    DrugCatalogueSelect,
    SupplierSelect
  },
  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: {
        category: '环境检测',
        pcPerson: '',
        pcPersonId: '',
        pcDepart: '',
        samplePoint: '',
        code: '',
        name: '',
        unit: '',
        spec: '',
        lotNum: '',
        catalogueId: '',
        remark: ''
      },
      ruleValidate: {
        category: [
          { required: true, message: '检测类型不能为空', trigger: 'change' }
        ],
        code: [{ required: true, message: '物料编号不能为空' }],
        name: [
          { required: true, message: '物料名称不能为空', trigger: 'change' }
        ]
      },
      showModal: false,
      testType: [
        {
          name: '环境检测'
        }
      ],
      footerList: [
        { id: '', name: '取消', type: '' },
        { id: '', name: '保存', type: 'primary' }
      ],
      groupData: [],
      itemIds: [],
      itemIdsEdit: [],
      orgList: [],
      edit: true,
      optionsTime: {
        disabledDate: function(date) {
          return date && date.valueOf() > Date.now()
        }
      }
    }
  },
  methods: {
    _testResult(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

        this.formObj = formObj

        console.log('this.formObj--', this.formObj)
        this.formObj.category = formObj.category
        this.modalTitle = '编辑报检信息'
        this.$refs.itemModal._getItem(formObj.id)
      }
      this._getUserGroup()
      this._getCategory()
    },
    _getCategory: async function() {
      const result = await drugSample.otherList()
      if (result) {
        this.testType = result.records
      }
    },
    _getUserGroup: async function() {
      const data = {}
      const result = await drugSample.page(data)
      if (result) {
        this.groupData = result
      }
    },
    _groupChange(data) {
      if (data) {
        this.formObj.groupName = data.label
        this.formObj.groupId = data.value
      } else {
        this.formObj.groupName = ''
        this.formObj.groupId = ''
      }
    },
    _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 } = this.formObj
          data.itemIds = this.itemIds
          this._save({
            ...data,
            category,
            catalogueId
          })
        } else {
          this.$Message.error('表单验证失败')
          this._hideLoading()
        }
      })
    },
    // 添加、编辑保存
    _save: async function(data) {
      // 添加
      if (this.$string(this.id).isEmpty()) {
        const result = await drugSample.addEnvRegister(data)
        this._resultChange(result, '添加成功')
      } else {
        // 编辑
        data.itemIds = this.itemIdsEdit.join(',')
        const result = await drugSample.edit({
          id: this.formObj.id,
          obj: data
        })
        this._resultChange(result, '编辑成功')
      }
    },
    // 请检时间
    _obtainSampleTime(data) {
      this.formObj.pcTime = data
    },

    _askEndTime(data) {
      this.formObj.aeTime = 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('obtainSampler')
    },
    _userData(data, msg) {
      // 选择人员返回数据
      if (msg === 'obtainSampler') {
        // 选择取样人取样人
        this.formObj.obtainSampler = data.realname
        this.formObj.obtainSamplerId = 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>
