<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" :key="item.itemCd" :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.weituoztMc" placeholder="请选择委托状态" clearable style="width: 200px;">
                <el-option v-for="item in weituozt" :key="item.zhuangtaibm" :label="item.zhuangtaimc"
                           :value="item.zhuangtaimc"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="提交时间" prop="">
              <el-date-picker v-model="query.tijiaosj" 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>
    <ButtonBar area="top" @search="handleSearch" @cancel="handleCancel" @commit="handleCommit" @add="handleAdd"
               @generate="handleGenerate"></ButtonBar>
    <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 prop="quyangsj" label="取样时间" width="180" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column 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="lotName" label="批次名称" width="200" header-align="center" align="center"
            show-overflow-tooltip></el-table-column> -->
        <el-table-column prop="weituoztMc" label="委托状态" width="180" header-align="center" align="center"
                         show-overflow-tooltip></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="weituolx" label="委托类型" width="120" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="chuangjianname" label="创建人" width="100" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="tijiaoname" label="提交人" width="100" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="tijiaosj" label="提交时间" width="180" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column prop="zhiyangsj" label="制样时间" width="200" header-align="center" align="center"
                         show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" header-align="center" align="center" width="200px" fixed="right">
          <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-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 :close-on-click-modal="false" draggable title="新增" v-model="dialogVisible" width="1200px" top="5vh"
               @open="openDialog">
      <el-form :model="form" label-width="120px" label-position="right" inline ref="ruleFormRef" :rules="rules">
        <el-form-item label="样品类型" prop="smpType">
          <el-select v-model="form.smpType" placeholder="请选择样品类型" clearable style="width: 200px;" @change="handleChangeYCG">
            <el-option label="过程委托" value="G"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物料类别" prop="leibiemc">
          <el-select v-model="form.leibiemc"  placeholder="请选择物料类别" filterable clearable style="width: 200px;">
            <el-option v-for="item in YCGList" :key="item.itemCd" :label="item.itemNm"
                       :value="item.itemNm"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="班次" prop="banCi" clearable>
          <el-select v-model="form.banCi" placeholder="请选择班次" clearable style="width: 200px;">
            <el-option label="一(0点-8点)" value="一"></el-option>
            <el-option label="二(8点-16点)" value="二"></el-option>
            <el-option label="三(16点-24点)" value="三"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="生产时间" prop="shengchanTime" >
          <el-date-picker
              v-model="form.shengchanTime"
              type="date"
              placeholder="选择日期"
              clearable style="width: 200px;"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="生产类型" prop="weituolx">
          <el-select v-model="form.weituolx"  placeholder="请选择委托类型" filterable clearable style="width: 200px;">
            <el-option label="生产委托" value="生产委托"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="委托数目" prop="num" v-show="form.weituolx === '试验委托'">
          <el-input-number v-model="form.num" :min="1" :max="10"></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 ButtonBar from "@/components/ButtonBar.vue";
import SearchBox from "@/components/SearchBox.vue";
import {
  ref,
  reactive,
  onMounted,
  getCurrentInstance
} from 'vue'
import style from '@/tools/style'
import {ElMessage, ElMessageBox} from "element-plus";


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

const {proxy} = getCurrentInstance()
const cardBodyStyle = ref(style.card)
const dialogVisible = ref(false)
const form = ref({
  leibiemc: '',
  weituoztMc: '',
  weituotype: '',
  smpType: 'G',
  chuangjianname: '',
  tijiaoname: '',
  tijiaosj: '',
  zhiyangsj: '',
  leibieid: '',
  erpbm: '',
  gonghuodw: '',
  gonghuodwid: '',
  contractNo: '',
  shouhuodw: '',
  shouhuodwid: '',
  banCi:'',
  shengchanTime:'',
  weituolx:'',
  num:''
  // shengchanTime:new Date().toISOString().split('T')[0]
})
const ruleFormRef = ref()
const tableData = ref([])
const query = ref({
  leibiemc: '',
  weituoztMc: '',
  smpType: 'G',
  yunshufs: '',
  tijiaosj: '',
})
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 YCGList = ref([])
const handleChangeYCG = ()=>{
  console.log(form.value.smpType,'form.smpType')
  if(!form.value.smpType){
    return
  }
  form.value.leibiemc = ''
  var url = 'sci/platform/getYCG'
  var param = {
    smpType: form.value.smpType,
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      console.log(response.data)
      YCGList.value = response.data.data
      console.log(YCGList.value,'YCGList.value')

    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
// 数据字典
const optionShiftList = ref([])
const getDic = () => {
  var url = 'framework/Common/querySelector'
  var param = {
    type: 'PRD_OPER_SHIFT'
  }
  proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      optionShiftList.value = response.data.data
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}

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


// ==========按钮功能===========
// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getTableData()
}
// 撤回
const handleCancel = () => {
  console.log('撤回防法')
  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要撤回的数据!'
    })
    return
  }
  var ids = []
  let dept = localStorage.getItem('dept')
  dept = JSON.parse(dept)
  let deptCode = dept[0].deptCode
  var userName = localStorage.getItem('userDesc')
  multipleSelection.value.forEach((item, index) => {
    ids.push(item.id)
  })
  var userName = localStorage.getItem('userDesc')
  var url = 'sci/platform/cancel'
  var param = {
    ids: JSON.stringify(ids),
    userName: userName,
    deptCode
  }
  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
      });
    }
  })
}
// 提交
const handleCommit = () => {
  console.log('提交方法')
  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择要提交的数据!'
    })
    return
  }
  let dept = localStorage.getItem('dept')
  dept = JSON.parse(dept)
  let deptCode = dept[0].deptCode
  var ids = []
  multipleSelection.value.forEach((item, index) => {
    ids.push(item.id)
  })
  var userName = localStorage.getItem('userDesc')
  var url = 'sci/platform/commit'
  var param = {
    ids: JSON.stringify(ids),
    userName: userName,
    deptCode
  }
  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
      });
    }
  })
}
// 新增
const handleAdd = () => {
  // console.log('新增')
  form.value = {
    weituolx:'生产委托'
  }
  form.smpType = 'G'

  dialogVisible.value = true
}

const data = ref()

const getData = async () => {

  var url = 'syi/checkPlan/queryTable'
  var param = {}
  await proxy.$axios.get(url, param).then(response => {
    if (response.data.code == '0') {
      data.value = response.data.data
    } else {
      ElMessage.error('操作失败！' + response.data.msg)
    }
  })
}
let dept = localStorage.getItem('dept')
dept = JSON.parse(dept)
let deptCode = dept[0].deptCode
// 保存
const handleSave = async (ruleFormRef) => {
  await getData()
  console.log(data.value, 'data')

  typeList.value.forEach(x => {
    if (x.itemNm == form.value.leibiemc) {
      form.value.leibieid = x.itemCd
      form.value.erpbm = x.itemCd
    }

  })
  // 检查是否在 tableData.value 中存在 leibieid 与 form.value.leibieid 相等的情况
  console.log(form.value.leibieid,'leibieid')

  const matched = data.value.some(y => form.value.leibieid == y.leibieid);
  console.log(matched, 'matched')

  if (!matched) {
    ElMessage.error('请先对该物料进行配置');
    return;
  }


  gongsiList.value.forEach(x => {
    if (form.value.gonghuodw == x.tradePartnerName) {
      form.value.gonghuodwid = x.tradePartnerCode
    }
  })
  gongsiList.value.forEach(x => {
    if (form.value.shouhuodw == x.tradePartnerName) {
      form.value.shouhuodwid = x.tradePartnerCode
    }
  })

  let userName = localStorage.getItem('userDesc')
  ruleFormRef.validate((valid, fields) => {
    if (valid) {
      let dept = localStorage.getItem('dept')
      dept = JSON.parse(dept)
      let deptCode = dept[0].deptCode
      var url = 'sci/platform/save'
      var param = {
        json: JSON.stringify(form.value),
        userName: userName,
        deptCode
      }
      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 multipleSelection = ref([])
const handleSelectionChange = (val) => {
  multipleSelection.value = val
  console.log(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 = 'cot/SignRequest/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 handleEditBatch = () => {
  console.log('handleEditBatch')
  if (multipleSelection.value.length != 1) {
    ElMessage({
      type: 'warning',
      message: '请选择一条数据编辑!'
    })
    return
  }
  handleEdit(multipleSelection.value[0])
}

// 生成
const handleGenerate = () => {
  console.log('handleGenerate')
}


// 删除
const handleDelete = (row) => {
  if (!((row.weituoztMc === '委托创建' && row.weituoztBm === 'ZT00') || (row.weituoztMc === '委托提交' && row.weituoztBm === 'ZT05'))) {
    ElMessage.error('该委托类型不能操作');
    return;
  }

  ElMessageBox.confirm(
      '确定删除本条记录?',
      '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
        draggable: true,
      }
  )
      .then(() => {
        var userName = localStorage.getItem('userDesc')
        var url = 'sci/platform/remove'
        var param = {
          id: row.id,
          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
            });
          }
        });
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消',
        })
      })
}
// 编辑
const handleEdit = (row) => {
  if (!((row.weituoztMc === '委托创建' && row.weituoztBm === 'ZT00') || (row.weituoztMc === '委托提交' && row.weituoztBm === 'ZT05'))) {
    ElMessage.error('该委托类型不能操作');
    return;
  }

  form.value = JSON.parse(JSON.stringify(row))
  dialogVisible.value = true
}

// ==========查询数据===========
const getTableData = () => {
  var url = 'sci/platform/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.records[0])
      console.log(tableData.value)
      totalRows.value = response.data.data.total
    } 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()
}

const rules = reactive({
  leibiemc: [{
    required: true,
    message: '请选择物料',
    trigger: 'change' | 'blur'
  }],
  contractNo: [{
    required: true,
    message: '请输入',
    trigger: 'change' | 'blur'
  }],
  gonghuodw: [{
    required: true,
    message: '请选择',
    trigger: 'change' | 'blur'
  }],
  shouhuodw: [{
    required: true,
    message: '请选择',
    trigger: 'change' | 'blur'
  }],
  smpType: [{
    required: true,
    message: '请选择',
    trigger: 'change' | 'blur'
  }],
  banCi: [{
    required: true,
    message: '请选择',
    trigger: 'change' | 'blur'
  }],
  shengchanTime: [{
    required: true,
    message: '请选择',
    trigger: 'change' | 'blur'
  }],
  weituolx: [{
    required: true,
    message: '请选择',
    trigger: 'change' | 'blur'
  }],
})
</script>

<style scoped></style>