<template>


  <div>
    <el-card :body-style="cardBodyStyle">
      <el-form :inline="true">
        <el-form-item label="物料名称" style="margin-bottom: 5px;" prop="name">
          <el-input v-model="query.name" placeholder="请输入" clearable></el-input>
        </el-form-item>
      </el-form>
    </el-card>
    <ButtonBar area="top" @search="handleSearch" @remove="handleRemoveBatch"></ButtonBar>
    <el-card :body-style="cardBodyStyle">
      <el-table :data="tableData" border highlight-current-row @selection-change="handleSelectionChange"
                row-key="id">
        <el-table-column type="selection" fixed></el-table-column>
        <el-table-column v-if="true" prop="id" label="ID" width="0" type="" header-align="center" align="center"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="name" label="名称" width="0" header-align="center" align="center"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="remark" label="数据类型" width="0" header-align="center" align="center"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column v-if="true" prop="qichezpcs" label="汽车组批车数" width="0" header-align="center"
                         align="center"
                         show-overflow-tooltip>
          <template #default="scope">
            <span>{{ calculateTotalIntervalQC(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-if="true" prop="huochezpcs" label="火车组批车数" width="0" header-align="center"
                         align="center"
                         show-overflow-tooltip>
          <template #default="scope">
            <span>{{ calculateTotalIntervalHC(scope.row) }} </span>
          </template>
        </el-table-column>
        <el-table-column v-if="true" prop="jiangesj" label="间隔时间(小时)" width="0" header-align="center"
                         align="center "
                         show-overflow-tooltip>
          <template #default="scope">
            <span>{{ calculateTotalInterval(scope.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" header-align="center" align="center" width="200px">
          <template #default="scope">
            <el-button plain type="warning" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button plain type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card :body-style="cardBodyStyle">
      <el-pagination :current-page="currentPage" :page-size="pageSize" :page-sizes="pageSizes" :total="totalRows"
                     background="background" layout="total, sizes, prev, pager, next, jumper"
                     @size-change="handleSizeChange"
                     @current-change="handleCurrentChange">
      </el-pagination>
    </el-card>
    <el-dialog custom-class="centered-form" :close-on-click-modal="false"></el-dialog>

    <el-dialog custom-class="centered-form" :close-on-click-modal="false" draggable :title="title_dialog"
               v-model="dialogVisible" width="1200px"
               top="5vh" @open="openDialog">
      <el-form :model="form" border label-width="120px" label-position="left" inline ref="ruleFormRef" :rules="rules">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" clearable style="width: 200px"></el-input>
        </el-form-item>

        <el-form-item label="汽车组批数" prop="qichezpcs">
          <el-input-number min="0" v-model="form.qichezpcs" clearable style="width: 200px"
                           :disabled="form.remark==='产品类别'"></el-input-number>
        </el-form-item>
        <el-form-item label="火车组批数" prop="huochezpcs">
          <el-input-number min="0" v-model="form.huochezpcs" clearable style="width: 200px"
                           :disabled="form.remark==='产品类别'"></el-input-number>
        </el-form-item>
        <el-form-item label="间隔时间(小时)" prop="jiangesj">
          <el-input-number v-model="form.jiangesj" min:0 clearable style="width: 200px"
                           :disabled="form.remark==='产品类别'"></el-input-number>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="handleSave(ruleFormRef)">保存</el-button>
          <el-button type="danger" @click="handleCancelSave">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>


import {
  ref,
  reactive,
  onMounted,
  getCurrentInstance
} from 'vue'

const {
  proxy
} = getCurrentInstance()

import tools from '@/tools'
import {ElMessage, ElMessageBox} from "element-plus";
import ButtonBar from "@/components/ButtonBar.vue";

const cardBodyStyle = ref(tools.style.card)
const inputStyle = ref(tools.style.input)

onMounted(() => {
  // handleSearch()
  // test()
  // queryNBHyjg()
  cancelUpload()
  // uploadMES()
})


/**
 *   查询
 */
const cancelUpload = ()=>{
  var weituoid = 'WT202412040002'
  var userId = '122'
  var userName = '123'
  var deptCode = '123'
  var url = 'sci/min/cancelUploadMES'
  var param = {
    weituoId:weituoid,
    userId:userId,
    userName:userName,
    deptCode:deptCode
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      ElMessage.warning('操作成功！')
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}


const uploadMES = ()=>{
  var url = 'sci/min/uploadMES'
  var param = {}
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      console.log(response.data.data,"测试")
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}


var weituoid = 'WT202411070001'

const queryNBHyjg = ()=>{
  var url = 'sci/JkJlxx/queryNBHyjg'
  var param = {
    weituoid:weituoid
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      console.log(response.data.data,"测试")
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}

var zph = 'ZP202412100001'

const test = ()=>{
  var url = 'sci/JkJlxx/queryHyjg'
  var param = {
    zph:zph
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      console.log(response.data.data,"测试")
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}

const treeData = ref([])
const query = ref({
  name: '',
  erpbm: ''
})
const tableData = ref([])
const handleSearch = () => {
  currentPage.value = 1
  getTableData()
}

const getTableData = () => {
  var url = 'syi/Leibie/query'
  var param = {
    page: currentPage.value,
    rows: pageSize.value,
    params: JSON.stringify(query.value)
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      tableData.value = response.data.data.records
      // console.log(response.data.data)
      console.log(tableData.value)
      totalRows.value = response.data.data.total
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}

// 递归计算间隔时间(小时)总和，忽略 remark 为 '产品类别' 的节点
const calculateTotalInterval = (row) => {
  let total1 = 0;

  // 如果 remark 为 '具体产品'，则加上 jiangesj 的值
  if (row.remark === '具体产品') {
    total1 += +row.jiangesj || 0;

  }

  // 如果有子节点，递归处理
  if (row.children && row.children.length > 0) {
    row.children.forEach(child => {
      total1 += +calculateTotalInterval(child); // 递归计算子节点的间隔时间
    });
  }

  return total1
};
// 递归计算汽车组批数总和，忽略 remark 为 '产品类别' 的节点
const calculateTotalIntervalQC = (row) => {
  let total2 = 0;

  // 如果 remark 为 '具体产品'，则加上 qichezpcs 的值
  if (row.remark === '具体产品') {
    total2 += +row.qichezpcs || 0;

  }

  // 如果有子节点，递归处理
  if (row.children && row.children.length > 0) {
    row.children.forEach(child => {
      total2 += +calculateTotalIntervalQC(child); // 递归计算子节点的汽车数
    });
  }

  return total2
};

// 递归计算火车组批数总和，忽略 remark 为 '产品类别' 的节点
const calculateTotalIntervalHC = (row) => {
  let total3 = 0;

  // 如果 remark 为 '具体产品'，则加上 huochezpcs 的值
  if (row.remark === '具体产品') {
    total3 += +row.huochezpcs || 0;

  }

  // 如果有子节点，递归处理
  if (row.children && row.children.length > 0) {
    row.children.forEach(child => {
      total3 += +calculateTotalIntervalHC(child); // 递归计算子节点的间隔时间
    });
  }

  return total3
};
/**
 * 添加时获取树形选择器数据
 *
 */
const getTreeData = () => {
  treeData.value = []
  var url = 'syi/Leibie/getTree'
  var param = {}
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {

      response.data.data.forEach(x => {
        const treeDataNode = processNode(x)
        treeData.value.push(treeDataNode.value)
        console.log(treeData.value)
      })
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}

const processNode = (node) => {
  const data = ref({
    label: '',
    value: '',
    children: []
  })
  data.value.label = node.name
  data.value.value = node.id

  if (node.children && node.children.length > 0) {
    node.children.forEach(childNode => {
      // 递归处理子节点
      const childData = processNode(childNode)
      data.value.children.push(childData.value)
    })
  }
  return data
}


/**
 *   查询
 */

/**
 * 分页
 */
const currentPage = ref(1)
const totalRows = ref(0)
const pageSizes = ref([5, 10, 20, 30, 40])
const pageSize = ref(5)
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  getTableData()
}
/**
 * 分页
 */


/**
 * 新增
 */
const dialogVisible = ref(false)
const form = ref({
  name: '',
  remark: '',
  erpbm: '',
  sortindex: '',
  enabled: '1',
  parentid: '',
  laiyuan: '录入',
  qichezpcs: '',
  huochezpcs: '',
  jiangesj: ''
})
const ruleFormRef = ref()
const rules = reactive({
  name: [{
    required: true,
    message: '请输入物料名称',
    trigger: 'change' | 'blur'
  }],
  qichezpcs: [{
    required: true,
    message: '请输入',
    trigger: 'change' | 'blur'
  }],
  huochezpcs: [{
    required: true,
    message: '请输入',
    trigger: 'change' | 'blur'
  }],
  jiangesj: [{
    required: true,
    message: '请输入',
    trigger: 'change' | 'blur'
  }]
})

const title_dialog = ref('')
const handleAdd = () => {
  title_dialog.value = '新增'
  form.value = {
    name: '',
    remark: '',
    erpbm: '',
    sortindex: '',
    enabled: '',
    laiyuan: '录入',
  }
  getTreeData()
  dialogVisible.value = true
}
/**
 * 新增
 */


/**
 * 保存、修改、删除
 */

const openDialog = () => {
}

const handleSave = (ruleFormRef) => {
  ruleFormRef.validate((valid, fields) => {
    if (valid) {
      var url = 'syi/Leibie/save'
      var param = {
        json: JSON.stringify(form.value),
      }
      proxy.$axios.post(url, param).then(response => {
        if (response.data.code == 0) {
          form.value = response.data.data
          ElMessage({
            message: '保存成功',
            type: 'success',
          })
          getTableData()
          dialogVisible.value = false
        } else {
          // ElMessage.error('操作失败！' + response.data.msg)
          ElMessage({
            message: '操作失败' + response.data.msg,
            type: 'error'
          })
        }
      })

    } else {
      console.log('error submit!', fields)
    }
  })
}
const handleCancelSave = () => {
  dialogVisible.value = false
}
const handleEdit = (row) => {
  title_dialog.value = '编辑'
  getTreeData()
  dialogVisible.value = true
  form.value = JSON.parse(JSON.stringify(row))
}
const handleDelete = (row) => {
  if (row.children && row.children.length > 0) {
    ElMessage({
      type: 'warning',
      message: '请先删除子节点或者使用批量删除功能',
    })
    return
  }
  ElMessageBox.confirm(
      '确定删除本条记录?',
      '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
      }
  )
      .then(() => {
        var url = 'syi/Leibie/remove'
        var param = {
          id: row.id
        }
        proxy.$axios.post(url, param).then(response => {
          if (response.data.code == 0) {
            ElMessage({
              type: 'success',
              message: '删除成功',
            })
            getTableData()
          } else {
            ElMessage({
              type: 'error',
              message: '删除失败' + response.data.msg
            });
          }
        });
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消',
        })
      })
}

/**
 * 保存、修改、删除
 */

const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const handleRemoveBatch = () => {
  console.log('handleRemoveBatch')

  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要删除的数据!'
    })
    return
  }

  ElMessageBox.confirm('此操作将删除该数据, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    var ids = []
    multipleSelection.value.forEach((item, index) => {
      ids.push(item.id)
    })
    var url = 'syi/Leibie/removeBatch'
    var param = {
      ids: JSON.stringify(ids)
    }
    proxy.$axios.post(url, param).then(response => {
      if (response.data.code == '0') {
        ElMessage({
          type: 'success',
          message: '操作成功!',
        });
        getTableData()
        dialogVisible.value = false
      } else {
        ElMessage({
          type: 'error',
          message: '操作失败!' + response.data.msg
        });
      }
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}

const handleChange = (row) => {
  var url = 'syi/Leibie/save'
  var param = {
    json: JSON.stringify(row),
  }
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == 0) {
      ElMessage({
        message: '保存成功',
        type: 'success',
      })
      getTableData()
      dialogVisible.value = false
    } else {
      // ElMessage.error('操作失败！' + response.data.msg)
      ElMessage({
        message: '操作失败' + response.data.msg,
        type: 'error'
      })
    }
  })
}


</script>

<style>
.centered-form .el-dialog__body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
</style>


