<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="请选择物料名称" filterable 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.quyangtjsj" placeholder="请选择" clearable style="width: 200px;">
                <el-option label="未提交" value="0"></el-option>
                <el-option label="已提交" value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="5">
            <el-form-item label="送样人" prop="">
              <el-select v-model="query.songyangid" placeholder="请选择送样人" filterable clearable style="width: 200px;">
                <el-option v-for="item in userData" :value="item.id" :label="item.userDesc"></el-option>

              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="取样时间" prop="">
              <el-date-picker
                  v-model="query.quyangsj"
                  type="datetime"
                  style="width: 200px;"
                  placeholder="请选择取样时间"
                  value-format="YYYY-MM-DD HH:mm:ss"
              />
            </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="取样编号" prop="">
              <el-input v-model="query.quyangbh" placeholder="请输入取样编号" clearable style="width: 200px;">
              </el-input>
            </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="8">
          <el-button type="primary" plain @click="handleSearch">查询</el-button>
          <el-button type="success" plain @click="handleCommit">取样完成提交</el-button>
          <el-button type="danger" plain @click="handleCancel">撤销</el-button>
          <el-button type="info" plain @click="handlePrintBatch">批量打印</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">
            <template #default="scope">
                <span>{{ scope.$index + (currentPage - 1) * pageSize + 1 }}</span>
            </template>
</el-table-column> -->
        <el-table-column prop="id" label="委托编号" width="180" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>

        <el-table-column prop="leibiemc" label="物料类别" width="150" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column v-if="true" prop="shengchanTime" label="生产时间" width="120" header-align="center"
                         align="center"
                         show-overflow-tooltip
                         >
        </el-table-column>
        <el-table-column prop="banCi" label="班次" width="80" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="weituoztMc" label="委托状态" width="200" header-align="center"
                         align="center"></el-table-column>
        <el-table-column prop="smpType" label="样品类型" width="120" header-align="center" align="center"
                         show-overflow-tooltip>
          <template #default="{ row }">
            {{ smpTypeList.find(item => item.bm === row.smpType)?.wtmc }}
          </template>
        </el-table-column>

        <el-table-column prop="quyangtjname" label="取样提交人" width="120" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="quyangtjsj" label="取样提交时间" width="200" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="quyangbh" label="取样编号" width="200" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="wulizybh" label="物理编号" width="200" header-align="center" align="center"
                         show-overflow-tooltip></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()
  queryWeiTuoZT()
  handleSearch()
  getTypeData()
  queryWTLXType()
  getUser()
  queryGS()
})


const {proxy} = getCurrentInstance()
const cardBodyStyle = ref(style.card)
const dialogVisible = ref(false)
const tableData = ref([])
const  query = ref({
  quyangsj: '',
  songyangid: '',
  leibiemc: '',
  weituoztMc: '',
  weituotype: '',
  yunshufs: '',
  tijiaosj: '',
  quyangtjsj: '0',
  quyangbh: '',
  shipName: '',
  chuangjiansj: '',
  gonghuodw: '',
  factName: '',
  lotNumber: '',
  lotName: '',
  contractNo: '',
  songyangname: '',
  zhiyangdwname: '',
  weituolx: '',
  smpType: 'G'
})


const userData = ref([])
const getUser = () => {
  var deptCode = 'D0117'
  var url = 'framework/SysUserDept/queryUsersByDeptCode'
  var param = {
    deptCode: deptCode
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      userData.value = response.data.data
      console.log(userData.value,"userData")
    }

  })
}

const getUserNameById = () => {
  var url = 'sci/user/getUserNameById'
  var param = {id: query.value.songyangid}
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      console.log(response.data.data, "username")
      query.value.songyangname = response.data.data.userDesc
    }
  })
}


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 weituozt = ref([])
const queryWeiTuoZT = () => {
  var url = 'sci/platform/queryWeiTuoZT'
  var param = {}
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      weituozt.value = response.data.data
      console.log(response.data.data)
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
const showA = ref(false)
const show = () => {
  showA.value = !showA.value
}
/**
 * 重置查询条件
 */
const reset = () => {
  Object.keys(query.value).map(key => {
    query.value[key] = ''
  })
}


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

//批量打印
const handlePrintBatch = () => {
  ElMessage({
    type: 'warning',
    message: '批量打印功能正在开发中...'


  })
  console.log('handlePrintBatch')
}

// 批量删除
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
  console.log(val)
}
var userName = localStorage.getItem('userDesc')

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

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

  if (!query.value.songyangid) {
    ElMessage({
      type: 'warning',
      message: '请选择送样人!'
    })
    return
  }
  getUserNameById()

  if (!query.value.quyangsj) {
    ElMessage({
      type: 'warning',
      message: '请选择取样时间!'
    })
    return
  }
  var ids = []
  multipleSelection.value.forEach(item => {
    console.log(item, "1111111111111111")
    ids.push(item.id)

  });
  ElMessageBox.confirm('此操作将会把数据进行提交, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    var url = 'sci/receive/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 = ''
        query.value.quyangsj = ''
        getTableData()
      } else {
        ElMessage({
          type: 'error',
          message: '操作失败!' + response.data.msg
        });
        query.value.songyangid = ''
        query.value.quyangsj = ''
        getTableData()
      }
    })
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消提交'
    })
  })
}

// 撤回
const handleCancel = () => {
  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要撤回的数据!'
    })
    return
  }
  var ids = []
  multipleSelection.value.forEach((item, index) => {
    ids.push(item.id)
  })
  var userName = localStorage.getItem('userDesc')
  var url = 'sci/receive/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
      });
    }
  })
}


// ==========查询数据===========
const getTableData = () => {

  var url = 'sci/receive/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(response.data.data.records[0])
      console.log(tableData.value)
      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 => {
        console.log(x, "22222222222")
        // 如果字段存在再加入数组，防止数据异常导致报错
        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 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)
    }

  })
}

/**
 * 分页
 */
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>