<template>
  <div>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :rules="queryRules"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-row>
        <el-form-item label="退料工程" prop="proName">
          <el-input
            v-model="queryParams.proName"
            placeholder="退料工程"
            clearable
            style="width: 240px"
            readonly
          />
        </el-form-item>
        <el-form-item label="退料班组" prop="teamName">
          <el-input
            v-model="queryParams.teamName"
            placeholder="退料单位"
            clearable
            style="width: 240px"
            readonly
          />
        </el-form-item>
        <el-form-item label="班组长" prop="backPerson">
          <el-input
            v-model="queryParams.backPerson"
            placeholder="请输入班组长"
            clearable
            style="width: 240px"
            readonly
          />
        </el-form-item>
        <el-form-item label="班组长电话" prop="phone">
          <el-input
            v-model="queryParams.phone"
            placeholder="请输入班组长电话"
            clearable
            style="width: 240px"
            :maxlength="11"
            readonly
          />
        </el-form-item>

        <el-form-item label="备注" prop="roleName">
          <el-input
            v-model="queryParams.remark"
            placeholder="请输入备注"
            clearable
            rows="1"
            readonly
            type="textarea"
            maxlength="100"
            style="width: 240px"
          />
        </el-form-item>
      </el-row>
      <el-row></el-row>
    </el-form>
    <el-table v-loading="loading" :data="equipmentList" @selection-change="handleSelectionChange">
     
      <el-table-column label="序号" type="index" align="center" min-width="80" />
      <el-table-column label="物资名称" align="center" prop="typeName" :show-overflow-tooltip="true" />
      <el-table-column label="规格型号" align="center" prop="typeModel" :show-overflow-tooltip="true" />
      <el-table-column label="计量单位" align="center" prop="unitName" />
      <el-table-column label="当前在用量" align="center" prop="num"></el-table-column>
      <el-table-column label="管理模式" align="center" prop="manageType">
        <template slot-scope="scope">
          <!-- 0编码1数量 -->
          <div v-if="scope.row.manageType == 0">编码管理</div>
          <div v-if="scope.row.manageType == 1">数量管理</div>
        </template>
      </el-table-column>
      <el-table-column label="退料数量" align="center" prop="preNum" min-width="100">
        <template slot-scope="scope">
          <div style="color: rgb(2, 167, 240)" @click="openAddCode(scope.row)" v-if="scope.row.manageType == 0">
            {{ scope.row.preNum }}
          </div>
          <div v-if="scope.row.manageType == 1">{{ scope.row.preNum }}</div>
        </template>
      </el-table-column>
      
      <el-table-column label="损坏价值判定" align="center" prop="apDetection" min-width="120"></el-table-column>

      <el-table-column label="备注" align="center" prop="remark" min-width="120">
      </el-table-column>
      <!-- <el-table-column label="附件" align="center" prop="file">
        <template slot-scope="scope">
          <div style="display: flex; align-items: center; justify-content: center">
            <el-button
              size="mini"
              type="text"
              @click="picturePreview(scope.row)"
              v-if="scope.row.bmFileInfos && scope.row.bmFileInfos.length > 0"
            >
              查看
            </el-button>
          </div>
        </template>
      </el-table-column> -->

      
    </el-table>

    <el-dialog title="编码退料" :visible.sync="open" width="1000px" append-to-body>
      <el-table :data="maCodeList" width="100%" height="450px">
        <el-table-column label="序号" type="index" width="55" align="center" />
        <el-table-column
          label="物资名称"
          prop="materialName"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          label="规格型号"
          prop="typeName"
          align="center"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column label="设备编码" prop="maCode" align="center" :show-overflow-tooltip="true"></el-table-column>
        <!-- <el-table-column label="设备状态" prop="maStatus" align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.ma_machine_status" :value="scope.row.maStatus" />
          </template>
        </el-table-column> -->
        <el-table-column
          label="损坏价值判定"
          prop="apDetection"
          align="center"
          width="160"
          :show-overflow-tooltip="true"
        >
        </el-table-column>
        <!-- <el-table-column label="附件" align="center" width="100">
          <template slot-scope="scope">
            <div style="display: flex; align-items: center; justify-content: center">
              <el-button
                size="mini"
                type="text"
                @click="picturePreview(scope.row)"
                v-if="scope.row.bmFileInfos && scope.row.bmFileInfos.length > 0"
              >
                查看
              </el-button>
            </div>
          </template>
        </el-table-column> -->
       
      </el-table>
      <div style="width: 100%; height: 50px; display: flex; justify-content: flex-end; align-items: center">
        <!-- <el-button type="primary" size="mini" @click="saveDevCode">保存</el-button> -->
        <el-button type="normal" size="mini" @click="open = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 图片查看弹窗 -->
    <el-dialog :visible.sync="dialogVisible" width="500px" height="500px">
      <img width="100%" height="500px" :src="dialogImageUrl" />
    </el-dialog>
  </div>
</template>

<script>
import {
  getProjectList,
  getUnitList,
  getAgreementInfoById,
  getDeviceTreeByAgreementId,
  addBackApply,
  getBackApplyInfo,
  editBackApply,
  getMachineById
} from '@/api/materialsStation'
import { mapState } from 'vuex'
import { getToken } from '@/utils/auth'
export default {
  name: 'ReturnApplyAdd',
  dicts: ['ma_machine_status'],
  props: {
    backId: {
      type: [String, Number]
    },
    agreementId: {
      type: [String, Number]
    },
    isView: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      rowData: {},
      maId: '',
      maData: {},
      maCodeList: [], //编码表格
      machineList: [], // 编码下拉选 集合
      //图片查看弹窗
      dialogImageUrl: '',
      dialogVisible: false,
      fileData: {},
      //上传
      upload: {
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/file/upload'
      },
      unitId: null,
      projectId: null,
      // 查询参数
      queryParams: {
        unitId: null,
        proId: null,
        agreementId: null, //协议id
        agreementCode: null, //协议code
        //班组长信息
        backPerson: '',
        phone: '',
        remark: '',
        //退料详情集合
        equipmentList: []
      },
      equipmentList: [],
      //退料详情单条模板
      leaseApplyDetailsItem: {
        createBy: null,
        // companyId: null,
        status: 0,
        typeId: null, //  树结构第4级   规格id
        typeName: '', //显示的设备类型
        typeCode: '', //显示的设备规格
        unitName: '', //显示的设备 单位
        useNum: '', //当前在用量
        remark: '', //单条备注
        preNum: 1 //预领数量
      },
      //
      queryRules: {
        unitId: [
          {
            required: true,
            message: '请选择退料单位',
            trigger: 'blur',
            type: 'number'
          }
        ],
        proId: [
          {
            required: true,
            message: '请选择退料工程',
            trigger: 'blur',
            type: 'number'
          }
        ]
      },
      unitList: [], //单位 集合
      proList: [], // 工程 集合

      deviceTypeTree: [], // 设备 树结构数据
      // 设备 树显示 配置
      deviceTypeTreeProps: {
        children: 'children',
        label: 'typeName',
        // multiple: false,
        value: 'typeId',
        multiple: true
      },
      // 选中的设备类型
      deviceType: null,
      createBy: '',
      rowId: '',
      propsKey: 1000
    }
  },
  mounted() {
    if (this.backId) {
      //编辑
      console.log(this.backId)
      this.rowId = this.backId
      this.GetViewByApply()
    }
  },
  computed: {
    ...mapState(['user'])
  },
  methods: {
    // 获取 来往单位 列表数据
    async GetUnitData(val) {
      const params = {
        projectId: this.queryParams.proId /*  */
      }
      const res = await getUnitList(params)
      this.unitList = res.data
      this.GetAgreementInfoById()
      // }
    },
    // 获取 工程名称 列表数据
    async GetProData(val) {
      const params = {
        unitId: this.queryParams.unitId
      }
      const res = await getProjectList(params)
      this.proList = res.data
      this.GetAgreementInfoById()
      // }
    },

    // 获取 设备树结构数据
    async GetDeviceTypeTreeFn(agreementId) {
      const params = {
        agreementId: agreementId
      }
      const res = await getDeviceTreeByAgreementId(params)
      console.log('resgetUseTypeTreee==========', res)
      this.deviceTypeTree = res.data
      //反显
      let selectList = []
      this.equipmentList.forEach(e => {
        selectList.push(this.getParentsById(this.deviceTypeTree, e.typeId))
      })
      this.deviceType = selectList
      this.$forceUpdate()
    },
    //树结构数据获取父
    getParentsById(list, id) {
      for (let i in list) {
        if (list[i].typeId == id) {
          //查询到就返回该数组对象的value
          return [list[i].typeId]
        }
        if (list[i].children) {
          let node = this.getParentsById(list[i].children, id)
          if (node !== undefined) {
            //查询到把父节把父节点加到数组前面
            node.unshift(list[i].typeId)
            return node
          }
        }
      }
    },
    // 获取 协议id
    async GetAgreementInfoById() {
      if (this.queryParams.unitId && this.queryParams.proId) {
        const params = {
          unitId: this.queryParams.unitId,
          projectId: this.queryParams.proId
        }
        const res = await getAgreementInfoById(params)
        console.log(res)
        if (!(res.data && res.data.agreementId)) {
          this.$message.error('当前单位和工程无协议！')
          this.queryParams.unitId = null
          this.queryParams.proId = null
          this.GetUnitData()
          this.GetProData()
        } else {
          this.queryParams.agreementId = res.data.agreementId
          this.queryParams.agreementCode = res.data.agreementCode
          this.GetDeviceTypeTreeFn(res.data.agreementId)
        }
      }
    },

    // 获取 任务详情数据
    async GetViewByApply(params) {
      const res = await getBackApplyInfo(this.rowId)
      if (res.msg && res.msg != '操作成功') {
        this.$message.warning(res.msg)
      }
      console.log(res)
      const data = res.data
      console.log(data)
      this.queryParams = data.backApplyInfo
      this.equipmentList = data.backApplyDetailsList
      // this.GetDeviceTypeTreeFn(data.backApplyInfo.agreementId)
      this.equipmentList.forEach(item => {
        const temp = item.typeName
        item.typeName = item.materialName
        item.typeModel = temp
      })
    },

    //是否可用勾选框
    selectable(row) {
      console.log(row)
      if (row.preNum != 0) {
        return true
      } else {
        return false
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.queryParams.equipmentList = selection
    },

    /** 保存按钮操作 */
    handleAdd() {
      this.$refs.queryForm.validate(async valid => {
        if (!valid) {
          return false
        } else {
          // let backApplyInfo = []
          if (this.equipmentList.length == 0) {
            this.$message.error('请先添加数据')
            return
          }
          if (this.queryParams.equipmentList.length == 0) {
            this.$message.error('请先勾选数据')
            return
          }

          const isNum = this.queryParams.equipmentList.some(item => item.preNum == '' || item.preNum == undefined)
          if (isNum) {
            this.$message.error('退料数量不能为空！')
            return
          }
          this.queryParams.backApplyInfo = {
            backPerson: this.queryParams.backPerson,
            phone: this.queryParams.phone,
            remark: this.queryParams.remark,
            agreementId: this.queryParams.agreementId
          }
          if (this.rowId != '') {
            let params = {
              id: this.rowId,
              backApplyInfo: this.queryParams.backApplyInfo,
              backApplyDetailsList: this.queryParams.equipmentList
            }
            if (params.backApplyInfo.signUrl) delete params.backApplyInfo.signUrl
            const res = await editBackApply(params)
            if (res.code == 200) {
              this.$message({ type: 'success', message: res.msg })
              setTimeout(() => {
                this.$emit('goBackPage')
              }, 1000)
            }
          } else {
            let params = {
              backApplyInfo: this.queryParams.backApplyInfo,
              backApplyDetailsList: this.queryParams.equipmentList
            }
            const res = await addBackApply(params)
            if (res.code == 200) {
              this.$message({ type: 'success', message: res.msg })
              setTimeout(() => {
                this.$emit('goBackPage')
              }, 1000)
            }
          }
        }
      })
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除所选择的数据项？')
        .then(() => {
          this.deviceType.forEach((e, index) => {
            if (e[3] === row.typeId) {
              this.deviceType.splice(index, 1)
              this.propsKey++
            }
          })
          this.equipmentList.forEach((item, index) => {
            if (item.id == row.id) {
              this.equipmentList.splice(index, 1)
            }
          })
        })
        .catch(() => {})
      // this.equipmentList.splice(row.index, 1)
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'system/role/export',
        {
          ...this.queryParams
        },
        `role_${new Date().getTime()}.xlsx`
      )
    },
    checkNum(row) {
      let maxNum = row.num
      if (row.preNum <= 1) {
        row.preNum = 1
      } else if (row.preNum >= maxNum) {
        row.preNum = maxNum
      }
    },
    /////// 设备类型树  切换
    async deviceTypeChange(val) {
      const deviceTypeList = this.$refs.deviceTypeCascader.getCheckedNodes()
      console.log(deviceTypeList)
      let tempList = []
      if (val.length > 0) {
        const items = val.map(e => {
          return e[3]
        })
        for (let i of items) {
          for (let z of deviceTypeList) {
            if (z.data.typeId === i) {
              const obj = JSON.parse(JSON.stringify(z.data))
              console.log(obj)
              obj.typeModel = obj.typeName
              obj.typeName = deviceTypeList[2].data.typeName
              obj.preNum = 0
              obj.apDetection = ''
              obj.remark = ''
              obj.maCodeList = []
              obj.bmFileInfos = []
              tempList.push(obj)
              break
            }
          }
        }
        const newDataListNew = [...this.equipmentList, ...tempList]
        const map = new Map()
        for (let item of newDataListNew) {
          if (!map.has(item.typeId)) {
            map.set(item.typeId, item)
          }
        }
        const newArray = [...map.values()]
        let newArray_array = []
        items.forEach(e => {
          newArray.forEach(j => {
            if (e == j.typeId) {
              newArray_array.push(j)
            }
          })
        })
        this.equipmentList = newArray_array
      } else {
        this.equipmentList = []
      }
    },
    //编码下拉选数据
    getMachineById(typeId) {
      let param = {
        teamId: this.queryParams.teamId,
        proId: this.queryParams.proId,
        typeId: typeId
      }
      getMachineById(param).then(res => {
        this.machineList = res.data
      })
    },
    changeMachine(val) {
      console.log(val)
      this.maData = this.machineList.find(option => option.maId == val)
      //  = this.machineList[index]
    },
    //编码类型-弹窗
    openAddCode(row) {
      this.rowData = row
      this.getMachineById(row.typeId)
      this.maId = ''
      this.maCodeList = []
      if (this.rowData.maCodeList && this.rowData.maCodeList.length > 0) {
        this.maCodeList = this.rowData.maCodeList
      }
      this.open = true
    },
    //查询添加
    handleAddCode() {
      console.log(this.rowData)
      console.log(this.maId)
      console.log(this.maData)
      if (this.maId != '') {
        let obj = {
          materialName: this.maData.materialName,
          typeId: this.maData.typeId,
          typeName: this.maData.typeName,
          maId: this.maData.maId,
          maCode: this.maData.maCode,
          maStatus: this.maData.maStatus,
          bmFileInfos: [],
          apDetection: ''
        }
        let index = this.maCodeList.findIndex(v => v.maId == this.maId)
        if (index > -1) {
          this.$message.error('设备编码已存在！')
        } else {
          this.maCodeList.push(obj)
        }
      } else {
        this.$message.error('请先填写设备编码！')
      }
    },
    /** 删除按钮操作 */
    handleDeleteCode(row) {
      this.maCodeList.splice(row.index, 1)
    },
    // 弹窗保存
    saveDevCode() {
      this.rowData.maCodeList = this.maCodeList
      this.rowData.preNum = this.maCodeList.length
      this.open = false
    }
  }
}
</script>
<style lang="scss">
.popper-select {
  .el-cascader-panel .el-scrollbar .el-checkbox {
    display: none;
  }

  .el-cascader-panel .el-scrollbar:nth-child(4) .el-checkbox {
    display: block !important;
  }
}
</style>
