<template>
  <div>
    <Modal v-model="showModal" v-drag width="1200">
      <p slot="header">
        {{ modalTitle }}
      </p>
      <div>
        <!--内容-->
        <Row>
          <!--查询-->
          <Col span="24">
          <Form id="search-sample-company" v-show="searchOpen" :label-width="100" inline onsubmit="return false">
            <label class="label-sign"></label>
            <Form-item label="试验名称:" class="search-item">
              <Input v-model="formObj.name" @on-enter="_formSearch" placeholder="请输入检测项目" clearable />
            </Form-item>
            <Form-item label="是否已添加科室:" class="search-item">
              <Select v-model="formObj.grouped" clearable name="groupId" style="width:150px" placeholder="请选择是否">
                <Option v-for="(item,index) in itemData" :value="item.value" :key="index">{{item.name}}</Option>
              </Select>
            </Form-item>
            <Form-item label="试验科室:" class="search-item">
              <Input v-model="formObj.groupName" @on-enter="_formSearch" placeholder="请输入试验科室" clearable />
            </Form-item>
            <Form-item label="试验编号:" class="search-item">
              <Input v-model="formObj.sampleCode" @on-enter="_formSearch" placeholder="请输入试样编号" clearable />
            </Form-item>
            <Form-item class="search-btn">
              <Button @click="_formSearch" type="primary">
                搜索
              </Button>
            </Form-item>
          </Form>
          </Col>
          <!--操作-->
          <Col span="24">
          <btn-list :msg="btn" :open="searchOpen" @on-result-change="_btnClick" class="contHide" show-search-btn="true"></btn-list>
          </Col>
          <!-- 表格 -->
          <Col span="24">
            <PTVXETable ref="pageTable" :table-height="tableHeight" :form-id="formId" :loading="true"
                        :get-page="getPage" @on-result-change="_tableResultChange"  is-edit select-data>
              <vxe-table-column
                v-for="item in pageColumns"
                :key="item.key"
                :field="item.key"
                :title="item.title"
                :min-width="item.width?item.width:200"
                :edit-render="item.editCell?{autofocus: 'input'}:null"
                :fixed="item.fixed?item.fixed:undefined" sortable>
              <template slot-scope="scope">
                <div v-if="item.detail">
                  <a @click.stop="_detailModal(scope.row)">{{ scope.row[item.key] }}</a>
                </div>
                <div v-else-if="item.key==='epibolyItem'" @click.stop="_handleRow(scope)">
                  <el-select v-if="showOption" v-model="scope.row.epibolyItem" @change="_optionChange(scope.row)" placeholder="请选择">
                    <el-option
                      v-for="(item,index) in subOptions"
                      :key="index"
                      :label="item.label"
                      :value="index"
                    />
                  </el-select>
                  <span v-if="!showOption">{{ scope.row[item.key]===0? '否':'是' }}</span>
                </div>
                <div v-else-if="item.key==='status'">
                  {{ scope.row[item.key].display }}
                </div>
                <div v-else-if="item.date">
                  {{ scope.row[item.key]?$dateformat(scope.row[item.key],'yyyy-mm-dd'):'' }}
                </div>
                <div v-else>
                  {{ scope.row[item.key] }}
                </div>
              </template>
                <template v-slot:edit="scope">
                  <div v-if="item.key==='shortName'" @click="_handleRow(scope)">
                    <el-input v-model="scope.row.shortName" @change="inputChange(scope.row)" name="shortName" placeholder="请输入英文简写">
                    </el-input>
                  </div>
                  <div v-if="item.key==='mainType'" @click="_handleRow(scope)">
                    <el-input v-model="scope.row.mainType" @change="inputMainTypeChange(scope.row)" name="mainType" placeholder="请输入大类">
                    </el-input>
                  </div>
                  <div v-if="item.key==='smallType'" @click="_handleRow(scope)">
                    <el-input v-model="scope.row.smallType" @change="inputSmallTypeChange(scope.row)" name="smallType" placeholder="请输入小类">
                    </el-input>
                  </div>
                  <div v-if="item.key==='testMethod'" @click="_handleRow(scope)">
                    <el-input v-model="scope.row.testMethod" @change="methodChange(scope.row)" name="testMethod" placeholder="请输入试验方法">
                    </el-input>
                  </div>
                  <div v-if="item.key==='groupName'" @click="_handleRow(scope)">
<!--                    <el-select @change="_selGroup" v-model="scope.row.groupName" placeholder="请选择" name="groupName" style="width: 100%">-->
<!--                      <el-option-->
<!--                        v-for="(item,index) in groupoptions"-->
<!--                        :key="index"-->
<!--                        :label="item.name"-->
<!--                        :value="item.name"-->
<!--                      />-->
<!--                    </el-select>-->
                    <AutoCompletes v-model="scope.row.groupName" :handle-obj="scope.row" :down-data="groupoptions" @on-result-change="_selGroup"
                                  style="editable:false" clearable
                                  placeholder="请选择试验室" show-key="name"></AutoCompletes>
                  </div>
                  <div v-if="item.key==='testBasis'" @click="_handleRow(scope)">
                    <AutoCompletes v-model="scope.row.testBasis" :handle-obj="scope.row" :down-data="testBasisList" @on-result-change="_selTestBasis"
                                   style="editable:false" clearable
                                   placeholder="请选择检测依据" show-key="name"></AutoCompletes>
                  </div>
                </template>
            </vxe-table-column>
            </PTVXETable>
          </Col>
        </Row>
      </div>
      <div slot="footer">
        <modal-footer ref="footerModal" :footer="footerList" @on-result-change="_footerResult" />
      </div>
    </Modal>
    <PrepareItemBatchEdit ref="batchEdit" @on-result-change="_pageByEntrustId"></PrepareItemBatchEdit>
  </div>
</template>
<script>
import http from '../../../api/http'
import { soilAptitude, soilEntrust } from '../../../api'
import AutoCompletes from '../../../components/base/AutoCompletes'
import PrepareItemBatchEdit from './PrepareItemBatchEdit'
export default {
  components: { AutoCompletes, PrepareItemBatchEdit },
  data() {
    return {
      formId: 'SampleItemManage',
      currentComponent: '',
      btn: [
        {
          type: 'success',
          id: '',
          name: '批量填写试验项目信息'
        },
        {
          type: 'error',
          id: '',
          name: '删除'
        }
      ],
      itemData: [
        {
          name: '是',
          value: 1
        },
        {
          name: '否',
          value: 0
        }
      ],
      iconMsg: [{ type: 'pt-a-end', id: '', name: '删除' }],
      sampleId: '', // 样品id
      entrustId: '',
      showModal: false,
      modalTitle: '管理检测项目',
      selectIds: [],
      itemId: '',
      index: '',
      showOption: true,
      searchOpen: true,
      selectData: {},
      getPage: {},
      groupoptions: [],
      testBasisList: [],
      currentRow: '',
      currentIndex: '',
      footerList: [
        { id: '', name: '取消', type: '' },
        { id: '', name: '关闭', type: 'primary' }
      ],
      pageColumns: [
        { title: '试验名称', key: 'name', width: 160 },
        { title: '试样编号', key: 'sampleCode', width: 160 },
        {
          title: '试验项目英文简写',
          key: 'shortName',
          width: 160,
          editCell: true
        },
        { title: '试验科室', key: 'groupName', width: 140, editCell: true },
        { title: '大类', key: 'mainType', width: 140, editCell: true },
        { title: '小类', key: 'smallType', editCell: true },
        { title: '检测依据', key: 'testBasis', width: 180, editCell: true },
        { title: '试验方法', key: 'testMethod', width: 180, editCell: true },
        { title: '状态', key: 'status', width: 180 }
      ],
      subOptions: [
        {
          value: '0',
          label: '否'
        },
        {
          value: '1',
          label: '是'
        }
      ],
      dateList: [],
      formObj: {
        name: undefined,
        sampleId: undefined,
        groupName: undefined,
        sampleCode: undefined,
        entrustId: undefined,
        grouped: undefined
      }
    }
  },
  computed: {
    tableHeight: function() {
      return this.$tableHeight('tableModal')
    }
  },
  methods: {
    _selectjudgeBasis(id, index) {
      console.log(id)
      this.itemId = id
      this.index = index
      this.$refs.EditModal._open()
    },
    _optionChange(data) {
      console.log(data)
      if (data.epibolyItem === 1) {
        this._submit(data.id)
      } else {
        this._cancelSub(data.id)
      }
    },
    _footerResult(name) {
      switch (name) {
        case '取消':
          this._cancel()
          break
        case '关闭':
          this._cancel()
          break
      }
    },
    _cancel() {
      this.$emit('on-result-change')
      this.$refs.pageTable._hideLoading()
      this.$refs.footerModal._hideLoading()
      this.showModal = false
    },
    _ok() {
      console.log(this.getPage.records)
    },
    _modalResult(data1, data2) {
      switch (this.currentComponent) {
        case 'CopyModal':
          if (data1 === 0) {
            this._copySample(data2)
          } else {
            this._copyAll(data2)
          }
          break
        default:
          this._search()
      }
    },
    _getGroupList: async function() {
      const result = await soilAptitude.getGroupList()
      if (result) {
        this.groupoptions = result
      }
    },
    _getTestBasisList: async function() {
      const result = await soilAptitude.getBasisList()
      if (result) {
        this.testBasisList = result
      }
    },
    _selGroup(msg, data, handleObj) {
      console.log(handleObj)
      if (msg === 'select') {
        this.getPage.records[this.currentIndex].groupName = data.name
        this.getPage.records[this.currentIndex].groupId = data.id
        const tempData = {}
        tempData.groupName = data.name
        tempData.groupId = data.id
        this._editItem(handleObj.id, tempData)
      }
    },
    _selTestBasis(msg, data, handleObj) {
      console.log(handleObj)
      if (msg === 'select') {
        this.getPage.records[this.currentIndex].testBasis = data.name
        const tempData = {}
        tempData.testBasis = data.name
        this._editItem(handleObj.id, tempData)
      }
    },
    inputChange(data) {
      const editData = {}
      editData.shortName = data.shortName
      this._editItem(data.id, editData)
    },
    inputMainTypeChange(data) {
      const editData = {}
      editData.mainType = data.mainType
      this._editItem(data.id, editData)
    },
    inputSmallTypeChange(data) {
      const editData = {}
      editData.smallType = data.smallType
      this._editItem(data.id, editData)
    },
    basisChange(data) {
      const editData = {}
      editData.testBasis = data.testBasis
      this._editItem(data.id, editData)
    },
    methodChange(data) {
      const editData = {}
      editData.testMethod = data.testMethod
      this._editItem(data.id, editData)
    },
    _editItem: async function(id, obj) {
      const result = await soilEntrust.editItem({ id: id, obj: obj })
      if (result) {
        this.$Message.success('修改成功')
      } else {
        this.$Message.warning('修改失败')
      }
    },
    _handleRow(data) {
      this.currentRow = data.row
      this.currentIndex = data.rowIndex
    },
    _dateChange(data) {
      this.formObj.ctimeBegin = data[0]
      this.formObj.ctimeEnd = data[1]
    },
    _btnClick(msg, componentName) {
      this.currentComponent = componentName
      this.$nextTick(function() {
        switch (msg) {
          case '批量填写试验项目信息':
            this._writeInfo()
            break
          case '提交分包':
            this._submitOutPack()
            break
          case '取消分包':
            this._cancelOutPack()
            break
          case '添加':
            this._editModal(false)
            break
          case '复制历史样品':
            this._copyHisSample()
            break
          case '导入样品':
            this._importSample()
            break
          case '导入检测项目':
            this._importItem()
            break
          case '导入检测项目包':
            this._importItemPackage()
            break
          case '复制历史样品检测项目':
            this._copyHisItem()
            break
          case '删除':
            this._deleteSelected()
            break
          case '导出':
            this._exportSample()
            break
          case '添加模拟样品':
            this._editImitateModal(false)
            break
          case 'search':
            this.searchOpen = !this.searchOpen
            break
        }
      })
    },
    _writeInfo() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请选择一条或多条数据！')
      } else {
        this.$refs.batchEdit._open(this.selectIds)
      }
    },
    _backData(data) {
      this.getPage.records[this.index].code = data.code
      this._codeEdit({ id: this.itemId, obj: { code: data.code } })
    },
    _codeEdit: async function(data) {
      const result = await soilEntrust.pageItemEdit(data)
      if (result) {
        this.$message.success('保存成功')
        this._pageByEntrustId()
      } else {
        this.$message.warning('保存失败')
      }
    },
    _compareSymbolEdit: async function(data) {
      const result = await soilEntrust.pageItemEdit(data)
      if (result) {
        this.$message.success('保存成功')
        this._pageByEntrustId()
      } else {
        this.$message.warning('保存失败')
      }
    },
    _limitValueEdit: async function(data) {
      const result = await soilEntrust.pageItemEdit(data)
      if (result) {
        this.$message.success('保存成功')
        this._pageByEntrustId()
      } else {
        this.$message.warning('保存失败')
      }
    },
    _unitEdit: async function(data) {
      const result = await soilEntrust.pageItemEdit(data)
      if (result) {
        this.$message.success('保存成功')
        this._pageByEntrustId()
      } else {
        this.$message.warning('保存失败')
      }
    },
    _submitOutPack() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选择一条')
      } else {
        this.$Modal.confirm({
          title: '提示',
          content: '确定分包这' + this.selectIds.length + '条',
          onOk: () => {
            this._submit()
          }
        })
      }
    },
    _cancelOutPack() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选择一条')
      } else {
        this.$Modal.confirm({
          title: '提示',
          content: '确定取消这' + this.selectIds.length + '条分包',
          onOk: () => {
            this._cancelSub()
          }
        })
      }
    },
    _submit: async function(data) {
      if (data !== undefined) {
        this.selectIds = data
      }
      const result = await soilEntrust.submitOutPack(this.selectIds)
      if (result) {
        this._resultChange('分包成功')
      }
    },
    _cancelSub: async function(data) {
      if (data !== undefined) {
        this.selectIds = data
      }
      const result = await soilEntrust.cancelOutPack(this.selectIds)
      if (result) {
        this._resultChange('取消分包成功')
      }
    },
    _exportSample() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选择一条样品')
      } else {
        this.$Modal.confirm({
          title: '提示',
          content: '确定导出这' + this.selectIds.length + '条样品',
          onOk: () => {
            http.open(
              '/food/v1/sample/company/export',
              { ids: this.selectIds.join(',') },
              '_blank'
            )
          }
        })
      }
    },
    _copyHisSample() {
      this.$refs.refModal._open(this.sampleId)
    },

    _iconClick(res, data, componentName, index) {
      this.currentComponent = componentName
      this.$nextTick(function() {
        switch (res) {
          case '编辑':
            this._editModal(true, data)
            break
          case '复制':
            this._copy(data)
            break
          case '删除':
            console.log(index)
            this._deleteById(data.id)
            break
          case '导出样品委托协议':
            this._exportAgreement(data.id)
            break
          case '附件':
            this.$refs.refModal._open(data.id, 'sampleId')
            break
        }
      })
    },
    _tableResultChange(msg, data) {
      const selectIds = []
      switch (msg) {
        case 'selectData':
          for (let i = 0; i < data.length; i++) {
            selectIds.push(data[i].id)
          }
          this.selectIds = selectIds
          this.selectData = data
          break
        // case 'iconClick':
        //   this._iconClick(data.name, data.rowData, data.componentName)
        //   break
        case 'page':
          this._pageByEntrustId()
          break
        case 'changeSize':
          this._pageByEntrustId()
          break
      }
    },
    _open(id) {
      this.formObj = this.$resetFields(this.formObj)
      this.dateList = []
      this.showModal = true
      this.sampleId = id // 委托id
      this.$refs.pageTable._hideLoading()
      this._pageByEntrustId()
    },
    _openByEntrustId(id) {
      this.formObj = this.$resetFields(this.formObj)
      this.dateList = []
      this.showModal = true
      this.entrustId = id // 委托id
      this.$refs.pageTable._hideLoading()
      this._pageByEntrustId()
      this._getGroupList()
      this._getTestBasisList()
    },
    _openRecord(id) {
      this.formObj = this.$resetFields(this.formObj)
      this.dateList = []
      this.showModal = true
      this.sampleId = id // 委托id
      this.$refs.pageTable._hideLoading()
      this.showOption = false
      this._pageByEntrustId()
    },
    _formSearch() {
      this.$refs.pageTable._pageChange(1)
    },
    _pageByEntrustId: async function() {
      this.selectIds = []
      Object.assign(this.formObj, this.$refs.pageTable._searchParams())
      this.formObj = this.$serializeForm(this.formObj)
      this.formObj.entrustId = this.entrustId
      const result = await soilEntrust.pageItemByEntrustId(
        this.$serializeForm(this.formObj)
      )
      if (result) {
        this.$refs.pageTable._hideLoading()
        this.getPage = result
        console.log(result)
      }
    },
    _page: async function() {
      Object.assign(this.formObj, this.$refs.pageTable._searchParams())
      this.formObj = this.$serializeForm(this.formObj)
      this.formObj.sampleId = this.sampleId
      const result = await soilEntrust.pageItem(
        this.$serializeForm(this.formObj)
      )
      if (result) {
        this.$refs.pageTable._hideLoading()
        this.getPage = result
        console.log(result)
      }
    },
    _deleteByIds(ids, content) {
      this.$Modal.confirm({
        title: '提示',
        content: content || '确定删除该记录？',
        onOk: () => {
          this._deleteOk(ids)
        }
      })
    },

    _deleteOk: async function(ids) {
      const result = await soilEntrust.experimentDeleteById(ids)
      if (result) {
        this._resultChange('删除成功！ ')
      }
    },
    _deleteById(id) {
      // 删除一条记录
      this._deleteByIds([id])
    },
    _deleteSelected() {
      // 批量删除
      const ids = this.selectIds
      if (ids.length === 0) {
        this.$Message.warning('请选择一条或多条数据！')
      } else {
        this._deleteByIds(ids, '确定删除 ' + ids.length + ' 条记录？')
      }
    },
    _detailModal(data) {},
    _editModal(edit, data) {
      if (edit) {
        console.log(data)
        this.$refs.sampleManageEdit._open(data)
      } else {
        // 添加
        this.$refs.refModal._open('', this.sampleId)
      }
    },
    _search() {
      this._pageByEntrustId()
    },
    _resultChange(msg) {
      this._pageByEntrustId()
      this.$Message.success(msg)
      this.$emit('on-result-change')
    },
    _copy(data) {
      this.$refs.copyModal._open(data.id, data.type)
    },
    // 导入检测项目
    _importItem() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选中一条样品数据！')
      } else {
        this.$refs.refModal._open(
          this.selectIds,
          this.selectData[0],
          this.selectData
        )
      }
    },
    // 导入检测项目包
    _importItemPackage() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选中一条样品数据！')
      } else {
        this.$refs.refModal._open(this.selectIds, 'sample-rel-package-item')
      }
    },
    _copyHisItem() {
      if (this.selectIds.length === 0) {
        this.$Message.warning('请至少选中一条样品数据！')
      } else {
        this.$refs.refModal._open(this.selectIds)
      }
    },
    _operationRecord(id) {
      // 操作日志
      this.$refs.recordModal._open(id)
    }
  }
}
</script>
