<template>
  <div>
    <el-card :body-style="cardBodyStyle">
      <el-form inline>
        <el-row :span="24">
          <el-col :span="5">
            <el-form-item label="物料名称" prop="">
              <el-select v-model="query.leibiemc" placeholder="请选择物料名称" clearable style="width: 200px;">
                <el-option v-for="item in typeList" :label="item.itemNm"
                           :value="item.itemNm"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="是否确认" prop="">
              <el-select v-model="query.weituoztBm" placeholder="请选择" clearable style="width: 200px;">
                <el-option label="全部" value="0"></el-option>
                <el-option label="未确认" value="1"></el-option>
                <el-option label="已确认" value="2"></el-option>
                <el-option label="已上传" value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="委托编号" prop="">
              <el-input v-model="query.id" placeholder="请输入委托编号" clearable style="width: 200px;">
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="5">
            <el-form-item label="取样编号" prop="">
              <el-input v-model="query.quyangbh" placeholder="请输入取样编号" clearable style="width: 200px;">
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="2">
            <el-button type="primary" @click="show" link>高级查询
              <el-icon v-if="showA">
                <ArrowUp/>
              </el-icon>
              <el-icon v-else>
                <ArrowDown/>
              </el-icon>
            </el-button>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="reset" link>重置</el-button>
          </el-col>
        </el-row>
        <el-row :span="24" v-if="showA">


          <el-col :span="5">
            <el-form-item label="供货单位">
              <el-select v-model="query.gonghuodw" placeholder="请选择供货单位" clearable style="width: 220px">
                <el-option v-for="item in gongsiList" :key="item.tradePartnerCode" :label="item.tradePartnerName"
                           :value="item.tradePartnerName"/>
              </el-select>
            </el-form-item>
          </el-col>



          <el-col :span="5">
            <el-form-item label="创建时间" prop="">
              <el-date-picker v-model="query.chuangjiansj" type="datetimerange" align="right" unlink-panels
                              range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
                              style="width: 403px;" value-format="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm:ss">
              </el-date-picker>
            </el-form-item>
          </el-col>

        </el-row>

      </el-form>
    </el-card>
    <el-card :body-style="cardBodyStyle">
      <el-row :span="24">
        <el-col :span="20">
          <el-button type="primary" plain @click="handleSearch">查询</el-button>
          <el-button type="success" plain @click="handleCommit">审核提交</el-button>
          <el-button type="danger" plain @click="handleCancelCommit">撤销审核</el-button>
          <el-button type="info" plain @click="handleExport">导出为Excel文件</el-button>
          <el-button type="danger" plain @click="handleCancel">退回审批</el-button>
          <el-button type="success"  @click="handleMES">上传MES</el-button>
          <el-button type="primary" plain @click="handleFujian">复检</el-button>
          <el-button type="danger" plain @click="handleDelete">删除复检</el-button>
        </el-col>
      </el-row>
    </el-card>

    <el-card :body-style="cardBodyStyle">
        <el-table :data="tableData" border highlight-current-row @selection-change="handleSelectionChange">
          <el-table-column type="selection" fixed></el-table-column>
          <el-table-column type="index" label="序号" align="center" width="60"fixed>
            <template #default="scope">
              <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column v-for="item in listKey.filter(key => key)"  :prop="item" :label="item" width="100" header-align="center"
                           align="center" show-overflow-tooltip>
          </el-table-column>
          <el-table-column prop="委托编号" label="委托编号" align="center" width="190" >
          </el-table-column>
          <el-table-column prop="物料名称" label="物料名称" align="center" width="120" >
          </el-table-column>
          <el-table-column prop="样品类型" label="样品类型" align="center" width="100">
          </el-table-column>
          <el-table-column prop="委托状态" label="委托状态" align="center" width="130">
          </el-table-column>
          <el-table-column prop="委托类型" label="委托类型" align="center" width="100">
          </el-table-column>

          <el-table-column prop="组批编号" label="组批编号" align="center" width="160">
          </el-table-column>
          <el-table-column prop="物理编号" label="物理编号" align="center" width="190">
          </el-table-column>
          <el-table-column prop="化学编号" label="化学编号" align="center" width="190">
          </el-table-column>
          <el-table-column prop="取样编号" label="取样编号" align="center" width="190">
          </el-table-column>
          <el-table-column prop="创建时间" label="创建时间" align="center" width="175">
          </el-table-column>
          <el-table-column prop="供货单位" label="供货单位" align="center" width="200">
          </el-table-column>

        </el-table>
        <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>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  onMounted,
  getCurrentInstance
} from 'vue'
import style from '@/tools/style'
import {ElMessage, ElMessageBox} from "element-plus";


onMounted(() => {
  queryType()
  handleSearch()
  getTypeData()
  queryWTLXType()
  queryGS()
})
const showA = ref(false)

const {proxy} = getCurrentInstance()
const cardBodyStyle = ref(style.card)
const dialogVisible = ref(false)
const tableData = ref([])
const query = ref({
  id: '',
  leibiemc: '',
  weituoztBm: '0',
  zupibh: '',
  weituotype: '',
  yunshufs: '',
  quyangbh: '',
  chuangjiansj: '',
  gonghuodw: '',
  smpType: 'Y,C'

})




// 查询所有公司
const gongsiList = ref([])
const queryGS = () => {
  gongsiList.value = []
  var url = 'sci/Weituogl/queryGS'
  var param = {}
  proxy.$axios.get(url, param).then(resp => {
    if (resp.data.code == '0') {
      gongsiList.value = resp.data.data
      console.log(gongsiList.value)
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }

  })
}

//获取部门编号
let dept = localStorage.getItem('dept')
dept = JSON.parse(dept)
let deptCode = dept[0].deptCode

const smpTypeList = ref([])
const queryWTLXType = () => {
  var url = 'sci/Weituogl/query_YLType'
  var param = {}
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      smpTypeList.value = response.data.data
      // console.log(smpTypeList.value)
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}

// 查询 物料名称
const typeList = ref([])
const queryType = () => {
  var url = 'sci/platform/queryType'
  var param = {}
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      typeList.value = response.data.data
      console.log(response.data.data)
      console.log(typeList.value)
      totalRows.value = response.data.data.total
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}

const show = () => {
  showA.value = !showA.value
}
/**
 * 重置查询条件
 */
const reset = () => {
  Object.keys(query.value).map(key => {
    query.value[key] = ''
  })
}


// ==========按钮功能===========
// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getTableData()
}

const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}
//批量打印
const handlePrintBatch = () => {
  ElMessage({
    type: 'warning',
    message: '批量打印功能正在开发中...'


  })
  console.log('handlePrintBatch')
}
var userName = localStorage.getItem('userDesc')

// 取样完成提交
const handleCommit = () => {


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

  var ids = []
  multipleSelection.value.forEach(item => {
    console.log(item, "1111111111111111")
    ids.push(item.委托编号)

  });
  ElMessageBox.confirm('此操作将会把数据进行提交, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    var url = 'sci/min/commit'
    var param = {
      ids: JSON.stringify(ids),
      json: JSON.stringify(query.value),
      userName: userName,
      deptCode: deptCode
    }
    proxy.$axios.post(url, param).then(response => {
      if (response.data.code == '0') {
        ElMessage({
          type: 'success',
          message: '操作成功!',
        });
        query.value.songyangid = ''
        getTableData()
      } else {
        ElMessage({
          type: 'error',
          message: '操作失败!' + response.data.msg
        });
      }
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消提交'
    })
  })
}

//撤销审核提交
const handleCancelCommit = () =>{
  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要撤回的数据!'
    })
    return
  }
  var ids = []
  multipleSelection.value.forEach((item, index) => {
    ids.push(item.委托编号)
  })
  var userName = localStorage.getItem('userDesc')
  var url = 'sci/min/cancelCommit'
  var param = {
    ids: JSON.stringify(ids),
    userName: userName,
    deptCode: deptCode
  }
  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
      });
      getTableData()
    }
  })
}

// 撤回
const handleCancel = () => {
  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要撤回的数据!'
    })
    return
  }
  var ids = []
  multipleSelection.value.forEach((item, index) => {
    ids.push(item.委托编号)
  })
  var userName = localStorage.getItem('userDesc')
  var url = 'sci/min/cancel'
  var param = {
    ids: JSON.stringify(ids),
    userName: userName,
    deptCode: deptCode
  }
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == '0') {
      ElMessage({
        type: 'success',
        message: '操作成功!',
      });
      query.value.songyangid = ''
      getTableData()

    } else {
      ElMessage({
        type: 'error',
        message: '操作失败!' + response.data.msg
      });
    }
  })
}
//上传MES
const handleMES = () => {
  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要上传的数据!'
    })
    return
  }
  var ids = []
  multipleSelection.value.forEach((item, index) => {
    ids.push(item.委托编号)
  })
  var url = 'sci/min/uploadMES'
  var param = {
    ids: JSON.stringify(ids),
    userName: userName,
    deptCode: deptCode
  }
  proxy.$axios.post(url, param).then(response => {
    if (response.data.code == '0') {
      ElMessage({
        type: 'success',
        message: '上传成功!',
      });
      query.value.songyangid = ''
      getTableData()

    } else {
      ElMessage({
        type: 'error',
        message: '上传失败!' + response.data.msg
      });
    }
  })
}

// 导出
const handleExport = () => {
  console.log('导出')
  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请至少选择一条数据导出!'
    })
    return
  }
  var params = {
    ids: multipleSelection.value.map(item => item.委托编号)
  }
  location.href = import.meta.env.VITE_BASE_API +
      '/sci/export/exportMin?params=' + encodeURIComponent(JSON.stringify(params))
}

// 复检
const handleFujian = () => {
  if (multipleSelection.value.length !== 1) {
    ElMessage({
      type: 'warning',
      message: '请选择一条数据进行复检!'
    })
    return
  }
  var ids = []
  multipleSelection.value.forEach((item, index) => {
    ids.push(item.委托编号)
  })

  ElMessageBox.confirm(
      '确定复检本条记录?',
      '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
      }
  )
      .then(() => {
        var userName = localStorage.getItem('userDesc')
        var url = 'sci/min/fujian'
        var param = {
          ids: JSON.stringify(ids),
          userName: userName,
          deptCode: deptCode
        }
        proxy.$axios.post(url, param).then(response => {
          if (response.data.code == '0') {
            ElMessage({
              type: 'success',
              message: '操作成功!',
            });
            query.value.songyangid = ''
            getTableData()

          } else {
            ElMessage({
              type: 'error',
              message: '操作失败!' + response.data.msg
            });
          }
        })
      }).catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消',
        })
      })

}

// 删除复检
const handleDelete = () => {
  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择复检数据进行删除!'
    })
    return
  }
  var ids = []
  multipleSelection.value.forEach((item, index) => {
    ids.push(item.委托编号)
  })

  ElMessageBox.confirm(
      '确定删除复检记录?',
      '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
      }
  )
      .then(() => {
        var userName = localStorage.getItem('userDesc')
        var url = 'sci/min/deleteFujian'
        var param = {
          ids: JSON.stringify(ids),
          userName: userName,
          deptCode: deptCode
        }
        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
            });
            getTableData()

          }
        })
      }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消',
    })
  })

}
// ==========查询数据===========
const orderedKeys = ref([]);
const listKey = ref([])

const getTableData = () => {
    var url = 'sci/min/queryTable'
    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(tableData.value)
        const dynamicKeysSet = new Set();
        tableData.value.forEach(currentObj => {
          Object.keys(currentObj).forEach(key => {
            if (!orderedKeys.value.includes(key)) { // 如果 key 不在 orderedKeys 中，添加到 dynamicKeysSet
              dynamicKeysSet.add(key);
            }
          });
        });
        // 将 dynamicKeysSet 转换为数组
        const sortedDynamicKeys = Array.from(dynamicKeysSet).sort((a, b) => {
          // 判断是否包含中文字符，包含中文字符的会返回 true
          const isChinese = text => /[\u4e00-\u9fa5]/.test(text);
          if (a.includes('HUAXUE') && b.includes('WULI')) return -1;
          if (a.includes('WULI') && b.includes('HUAXUE')) return 1;
          return 0; // 保持原顺序
        });

        // 将排序后的数组重新转换为 Set
        dynamicKeysSet.clear();
        sortedDynamicKeys.forEach(key => {
          key = key.substring(0, key.indexOf('_'));
          console.log(key)
          dynamicKeysSet.add(key)
        });

        console.log(dynamicKeysSet)
        // 将静态字段和动态字段合并，生成最终顺序的 listKey
        listKey.value = [...orderedKeys.value, ...Array.from(dynamicKeysSet)];
        listKey.value = listKey.value.filter(x => x !== 'ROW');
        console.log(listKey.value)
        tableData.value.forEach(x => {
          let y = Object.keys(x);
          y.forEach(name => {
            if (name.includes('_')) {
              // 新的属性名为截取到下划线之前的部分
              const newName = name.substring(0, name.indexOf('_'));
              // 为 x 对象添加新属性，并赋予原属性的值
              x[newName] = x[name];
              // 删除旧的属性
              delete x[name];
            }
          });

          // 根据样品类型匹配并替换
          smpTypeList.value.forEach(y => {
            if (x.样品类型 == y.bm) {
              x.样品类型 = y.wtmc;
            }
          });

          console.log(x);
        });

        totalRows.value = response.data.data.total
      } else {
        ElMessage.error('操作失败！' + response.data.msg)
      }
    })
  };

// ==========查询所有的下拉框数据===========
const weiTuoData = ref([])

const songYangNameData = ref([])
const zhiYangData = ref([])

const getTypeData = () => {
  // 定义URL
  var url = 'sci/receive/queryType'
  var param = {}
  // 发送GET请求
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      console.log(response.data.data, "111111111111")

      // 清空已有数据
      weiTuoData.value = []
      songYangNameData.value = []
      zhiYangData.value = []

      // 遍历返回的数据并推入数组
      response.data.data.forEach(x => {
        // 如果字段存在再加入数组，防止数据异常导致报错
        if (x.weituolx && !weiTuoData.value.some(item => item.value === x.weituolx)) {
          weiTuoData.value.push({
            label: x.weituolx,
            value: x.weituolx
          })
        }
        if (x.songyangname && !songYangNameData.value.some(item => item.value === x.songyangname)) {
          songYangNameData.value.push({
            label: x.songyangname,
            value: x.songyangname
          })
        }
        if (x.zhiyangdwname && !zhiYangData.value.some(item => item.value === x.zhiyangdwname)) {
          zhiYangData.value.push({
            label: x.zhiyangdwname,
            value: x.zhiyangdwname
          })
        }
      })
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  }).catch(error => {
    ElMessage.error('请求失败！' + error.message)
  })
}

/**
 * 查询供应单位数据
 */

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

<style scoped></style>