<template>
  <div id="addEquipment">
    <el-card style="position: relative;">
      <span>基本信息</span>
      <el-form :model="basicForm" :rules="basicRules" ref="basic" label-width="auto" :show-message="false">
        <el-row :gutter="10">

          <el-col :span="1.5">
            <el-form-item label="通用名称" prop="commonName">
              <el-input clearable :disabled="sonDisable" size="mini" v-model="basicForm.commonName">
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="注册名" prop="registrationName">
              <el-input clearable :disabled="sonDisable" size="mini" v-model="basicForm.registrationName">
              </el-input>
            </el-form-item>
          </el-col>
          
          <el-col :span="1.5">
            <el-form-item label="设备类别" prop="deviceCategory">
              <el-input clearable :disabled="sonDisable" size="mini" v-model="basicForm.deviceCategory">
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="适用科室" prop="departmentCode">
              <el-input clearable :disabled="sonDisable" size="mini" v-model="basicForm.departmentCode">
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="厂家名称" prop="factoryName">
              <el-input clearable :disabled="sonDisable" size="mini" v-model="basicForm.factoryName">
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="型号" prop="model">
              <el-input clearable :disabled="sonDisable" size="mini" v-model="basicForm.model">
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="1.5">
            <el-form-item label="参考价格" prop="referencePrice">
              <el-input clearable :disabled="sonDisable" size="mini" v-model="basicForm.referencePrice">
              </el-input>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row>
          <el-col :span="1.5">
            <el-form-item label="是否项目/厂家年度授权" prop="isProjectOrFactoryEmpower">
              <el-checkbox :disabled="sonDisable" true-label= '0' false-label= '2' v-model="basicForm.isProjectOrFactoryEmpower"></el-checkbox>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="文件上传" prop="sysMaterialDeviceOriginFileList">
            <el-upload
              :action="url"
              :headers="headers"
              :on-preview="handlePreview"
              :on-success='handleSuccess'
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              multiple
              :limit="1"
              :on-exceed="handleExceed"
              :file-list="basicForm.sysMaterialDeviceOriginFileList">
              <el-button size="small" type="primary" :disabled="sonDisable">点击上传</el-button>
              <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
            </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="1.5">
            <el-form-item label="参数" prop="parameters">
              <el-input type="textarea" rows=4 style="width: 900px" clearable :disabled="sonDisable" size="mini" v-model="basicForm.parameters">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="1.5">
            <el-form-item label="备注" prop="remark">
              <el-input type="textarea" rows=4 style="width: 400px" clearable :disabled="sonDisable" size="mini" v-model="basicForm.remark">
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <div class="btn_group">
        <el-button type="primary" size="mini"  @click="editPage" v-if="sonPageStu == 'check'">编辑</el-button>
        <el-button type="primary" size="mini"  @click="save" v-if="sonPageStu == 'add' || sonPageStu == 'edit'">保存</el-button>
        <el-button size="mini" plain @click="back">返回</el-button>
      </div>

      <div class="btn_grooup">
        <span>明细信息</span>
        <div>
          <el-button type="primary" size="mini" @click="addLine" v-if="!sonDisable">增行</el-button>
          <el-button type="primary" size="mini" @click="delLines" v-if="!sonDisable">删行</el-button>
        </div>
      </div>

      <ux-grid
        :data="basicForm.sysMaterialDeviceOriginItemList"
        border
        :cell-style="{ borderColor: '#c0c0c0' }"
        :header-cell-style="{ borderColor: '#c0c0c0' }"
        class="exporttable"
        height="410"
        max-height="410"
        style="font-size: 12px;"
        @selection-change="handleSelectionChange"
        ref="table"
        show-header-overflow="tooltip"
        show-overflow="tooltip"
        keep-source
        beautifyTable
        :checkbox-config="{highlight: true, trigger: 'row'}"
        :edit-config="{trigger: 'click', mode: 'row'}">
      >
          <ux-table-column resizable type="checkbox" width="50px" fixed="left"/>
          <!-- <ux-table-column resizable title="序号" type="index" align="center" width="50px"/> -->
          <ux-table-column resizable title="省份" align="center"  field="province" edit-render>
            <template v-slot:edit="scope">
              <el-select size="mini" :disabled="sonDisable" v-model="scope.row.province" filterable clearable placeholder="请选择">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
                <!-- <el-input clearable :disabled="sonDisable" size="mini" v-model="scope.row.province"/> -->
            </template>
          </ux-table-column>

          <ux-table-column resizable title="大区负责人" align="center"  field="largeZoneCommander" edit-render>
            <template v-slot:edit="scope">
                <el-input clearable :disabled="sonDisable" size="mini" v-model="scope.row.largeZoneCommander"/>
            </template>
          </ux-table-column>

          <ux-table-column resizable title="业务经理" align="center"  field="serviceManager" edit-render>
            <template v-slot:edit="scope">
                <el-input clearable :disabled="sonDisable" size="mini" v-model="scope.row.serviceManager"/>
            </template>
          </ux-table-column>

          <ux-table-column resizable title="售后工程师" align="center"  field="afterSalesEngineer" edit-render>
            <template v-slot:edit="scope">
                <el-input clearable :disabled="sonDisable" size="mini" v-model="scope.row.afterSalesEngineer"/>
            </template>
          </ux-table-column>
      </ux-grid>
    </el-card>

  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import { addEquipment, getEquipmentDetail, editEquipment } from '@/api/purchase/equipmentData.js'
export default {
  components: {
  },
  props: ['pageStu','row', 'disable'],
  model: {
    prop: 'isList',
    event: 'jugislist'
  },
  data() {
    return {
      // 不能直接改变props传来的值
      sonPageStu: this.pageStu,
      sonDisable: this.disable,
      basicForm: {
        id: '',
        commonName: '',
        registrationName: '',
        deviceCategory: '',
        departmentCode: '',
        factoryName: '',
        model: '',
        referencePrice: '',
        parameters: '',
        isDeleteFile: '',
        sysMaterialDeviceOriginItemList: [],
        sysMaterialDeviceOriginFileList: [],
        isProjectOrFactoryEmpower: '',
        remark: '',
      },
      sonModel: {
        province: null,
        largeZoneCommander: null,
        serviceManager: null,
        afterSalesEngineer: null,
        delFlag: '0'
      },
      basicRules: {},
      ids:[],
      delDemandItemList:[],
      headers: { Authorization: "Bearer " + getToken() },
      url: process.env.VUE_APP_BASE_API + '/device/origin/upload',
      options: [
        {value: '黑龙江省', label: '黑龙江省'},
        {value: '吉林省', label: '吉林省'},
        {value: '辽宁省', label: '辽宁省'},
        {value: '河北省', label: '河北省'},
        {value: '甘肃省', label: '甘肃省'},
        {value: '青海省', label: '青海省'},
        {value: '陕西省', label: '陕西省'},
        {value: '河南省', label: '河南省'},
        {value: '山东省', label: '山东省'},
        {value: '山西省', label: '山西省'},
        {value: '安徽省', label: '安徽省'},
        {value: '湖北省', label: '湖北省'},
        {value: '湖南省', label: '湖南省'},
        {value: '江苏省', label: '江苏省'},
        {value: '四川省', label: '四川省'},
        {value: '贵州省', label: '贵州省'},
        {value: '云南省', label: '云南省'},
        {value: '浙江省', label: '浙江省'},
        {value: '广东省', label: '广东省'},
        {value: '江西省', label: '江西省'},
        {value: '福建省', label: '福建省'},
        {value: '台湾省', label: '台湾省'},
        {value: '海南省', label: '海南省'},
        {value: '新疆维吾尔自治区', label: '新疆维吾尔自治区'},
        {value: '内蒙古自治区', label: '内蒙古自治区'},
        {value: '宁夏回族自治区', label: '宁夏回族自治区'},
        {value: '广西壮族自治区', label: '广西壮族自治区'},
        {value: '西藏自治区', label: '西藏自治区'},
        {value: '北京市', label: '北京市'},
        {value: '上海市', label: '上海市'},
        {value: '天津市', label: '天津市'},
        {value: '重庆市', label: '重庆市'},
        {value: '香港特别行政区', label: '香港特别行政区'},
        {value: '澳门特别行政区', label: '澳门特别行政区'},
      ]
    }
  },
  created() {
    if(this.pageStu == 'check') {
      console.log('数据', this.row)
      this.getDetails(this.row)
    } else if(this.pageStu == 'edit') {
      this.getDetails(this.row)
    } else if (this.pageStu == 'add') {

    }
  },
  methods: {
    getDetails(row) {
      getEquipmentDetail(row.id).then(res => {
        if (res.code === 200) {
          this.basicForm = res.data
        }
      })
    },
    editPage() {
      this.sonPageStu = 'edit'
      this.sonDisable = false
    },
    async save() {
      // return false
      if(this.basicForm.sysMaterialDeviceOriginItemList.length !== 0) {
        if (this.sonPageStu == 'add') {
          await addEquipment(this.basicForm).then(res => {
            if(res.code === 200) {
              this.$modal.notifySuccess("新增保存成功");
              this.back()
            }
          })
        } else if (this.sonPageStu == 'edit') {
          let list = []
          list.push(...this.basicForm.sysMaterialDeviceOriginItemList, ...this.delDemandItemList)
          // 深拷贝一下参数对象
          let param = JSON.parse(JSON.stringify(this.basicForm))
          console.log('深拷贝对象',param);
          param.sysMaterialDeviceOriginItemList = list
          await editEquipment(param).then(res => {
            if(res.code === 200) {
              this.$modal.notifySuccess("编辑保存成功");
              this.sonPageStu = 'check'
              this.sonDisable = true
              this.getDetails(this.row)
            }
          })
        }
      } else {
        this.$modal.notifyWarning("请填写明细信息");
      }
    },
    back() {
      this.$emit('jugislist', true)
      this.$emit('refresh')
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item =>{
        return item.id
      })
      console.log('选中数组', this.ids)
    },
    addLine() {
      const newLine = {...this.sonModel}
      this.basicForm.sysMaterialDeviceOriginItemList.push(newLine)
      console.log(this.basicForm.sysMaterialDeviceOriginItemList)
    },
    delLines() {
      let delArr = this.$refs.table.getCheckboxRecords()
      if (delArr.length !== 0) {
        delArr.forEach(item => {
          item.delFlag = '2'
        })
        console.log('kk',this.basicForm.sysMaterialDeviceOriginItemList)
        let delList = []
        delList = this.basicForm.sysMaterialDeviceOriginItemList.filter(item => {
          return item.delFlag == '2'
        })
        this.basicForm.sysMaterialDeviceOriginItemList = this.basicForm.sysMaterialDeviceOriginItemList.filter(item => {
          return item.delFlag == '0'
        })
        this.delDemandItemList.push(...delList)
      } else {
        this.$modal.notifyWarning('请至少选择一条明细！')
      }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      // 编辑删除了文件给标识
      if (this.sonPageStu == 'edit') {
        this.basicForm.isDeleteFile = '0'
      }
      this.basicForm.sysMaterialDeviceOriginFileList = []
    },
    handlePreview(file) {
      console.log(file);
      let link = document.createElement("a")
      link.download = file.name
      link.href = file.url
      link.click()
      window.URL.revokeObjectURL(link.href)
    },
    handleSuccess(response, file, fileList) {
      console.log(response)
      if (this.sonPageStu == 'edit') {
        this.basicForm.isDeleteFile = '0'
      }
      this.basicForm.sysMaterialDeviceOriginFileList = response.data
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择1个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      if(this.sonPageStu == 'check') {
        this.$modal.notifyWarning("详情态不允许删除");
        return false
      } else {
        return this.$confirm(`确定移除 ${ file.name }？`);
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.btn_group {
  // width: 100%;
  // margin: 20px 0;
  display: flex;
  justify-content: space-between;
  position: absolute;
  top: 10px;right: 20px;

}
.btn_grooup {
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
}
</style>