<template>
  <div class="page-container column-container">
    <!-- 搜索区 -->
    <el-form
      class="list-search-container"
      :model="queryParams"
      ref="queryRef"
      :inline="true"
    >
      <el-form-item class="section-title" label="咨询管理" />
      <el-form-item label="咨询部门：">
        <el-select
          v-model="queryParams.consultDepartment"
          placeholder="请选择咨询部门"
          style="width: 150px"
        >
          <el-option v-if=" qualityController&&technicianController" label="全部" value="-1" />
          <el-option v-if="technicianController" label="技术" value="0" />
          <el-option v-if="qualityController" label="品管" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="咨询类别：">
        <el-select
          v-model="queryParams.type"
          clearable
          placeholder="请选择类别"
          style="width: 130px"
        >
          <el-option label="全部" value="" />
          <el-option label="分选" value="0" />
          <el-option label="巡检" value="1" />
          <el-option label="交检" value="2" />
          <el-option label="首件检" value="3" />
          <el-option label="仪器室" value="4" />
          <el-option label="外协检" value="5" />
          <el-option label="出厂检" value="6" />
        </el-select>
      </el-form-item>
      <el-form-item label="放行状态：">
        <el-select
          v-model="queryParams.status"
          clearable
          placeholder="请选择放行状态"
          style="width: 130px"
        >
          <el-option label="全部" value="" />
          <el-option label="待回复" value="0" />
          <el-option label="不合格" value="1" />
          <el-option label="合格" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="计划单号/批次号：">
        <el-input
          placeholder="请输入关键字"
          v-model.trim="queryParams.lotCode"
          style="width: 120px"
          clearable
          @keyup.enter="handleQuery"
          @keydown.enter.prevent
        />
      </el-form-item>
      <el-form-item label="产品描述：">
        <el-input
          placeholder="请输入关键字"
          v-model.trim="queryParams.productDescription"
          style="width: 120px"
          clearable
          @keyup.enter="handleQuery"
          @keydown.enter.prevent
        />
      </el-form-item>
      <el-form-item label="问题描述：">
        <el-input
          placeholder="请输入关键字"
          v-model.trim="queryParams.content"
          style="width: 120px"
          clearable
          @keyup.enter="handleQuery"
          @keydown.enter.prevent
        />
      </el-form-item>
      <el-form-item>
        <el-button type="info" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 列表区 -->
    <div class="el-table-container">
      <div class="el-table-inner-container">
        <el-table
          ref="dataTable"
          v-loading="loading"
          border
          :data="dataList"
          highlight-current-row
          height="100%"
        >
          <el-table-column
            type="index"
            label="行号"
            width="50"
            align="center"
          />
          <el-table-column label="咨询部门" align="center" width="70">
            <template #default="scope">
              <span v-if="scope.row.consultDepartment === 0">技术</span>
              <span v-else>品管</span>
            </template>
          </el-table-column>
          <el-table-column label="咨询类别" align="center" width="80">
            <template #default="scope">
              <span v-if="scope.row.processInspectionId == 0">分选</span>
              <span v-if="scope.row.type == 'patrolInspection'">巡检</span>
              <span v-if="scope.row.type == 'deliveryInspection'">交检</span>
              <span v-if="scope.row.type == 'firstArticleInspection'">首件检</span>
              <span v-if="scope.row.type == 'instrumentRoomInspection'">仪器室</span>
              <span v-if="scope.row.type == 'outsourcedInspector'">外协检</span>
              <span v-if="scope.row.type == 'factoryInspection'">出厂检</span>
            </template>
          </el-table-column>
          <el-table-column label="放行状态" align="center" width="64">
            <template #default="scope">
              <span v-if="scope.row.status == 0">待回复</span>
              <span
                v-if="scope.row.status == 1"
                style="font-weight: 700; color: #f56c6c"
                >不合格</span
              >
              <span
                v-if="scope.row.status == 2"
                style="font-weight: 700; color: #67c23a"
                >合格</span
              >
            </template>
          </el-table-column>
          <el-table-column
            label="批次号"
            width="120"
            align="center"
            prop="lotCode"
          />
          <el-table-column
            label="产品描述"
            align="center"
            width="320"
            prop="productDescription"
          />
          <el-table-column
            label="工序"
            width="100"
            align="center"
            prop="processAlias"
          />
          <el-table-column label="问题描述" align="center" prop="content" />
          <el-table-column label="图片" width="220px" header-align="center" align="left" >
          <template #default="scope">
            <span >
              <el-image v-for="item,index in scope.row.pictureList" :key="index" :initial-index="index" style="width: 60px; height: 60px;margin-right:8px" :src="item" :preview-src-list="scope.row.pictureList" :preview-teleported="true"  />
            </span>
          </template>
        </el-table-column>
          <el-table-column
            label="技术负责人"
            align="center"
            width="90"
            prop="technicianName"
          />
          <el-table-column
            label="提交人"
            align="center"
            width="60"
            prop="nickName"
          />
          <el-table-column
            label="审核人"
            align="center"
            width="80"
            prop="reviewerName"
          />
          <el-table-column
            label="提交时间"
            align="center"
            width="144"
            prop="createTime"
          />
          <el-table-column label="操作" align="center" width="200" prop="consultResultId" fixed="right">
            <template #default="scope">
              <el-select placeholder="请选择" style="width: 140px" v-model.trim="scope.row.consultResultId" @change="handleChangeStatus(scope.row)">
            <el-option v-for="dict in resultList" :key="dict.value" :label="dict.label" :value="dict.value"  />
          </el-select>
              <!-- <el-button
                v-if="scope.row.status === 0 || scope.row.status === 1"
                type="success"
                icon="Check"
                @click="handleSetStatus('OK', scope.row)"
                >合格</el-button
              >
              <el-button
                v-if="scope.row.status === 0 || scope.row.status === 2"
                type="danger"
                icon="Close"
                @click="handleSetStatus('ERR', scope.row)"
                >不合格</el-button
              > -->
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </div>
</template>
<script setup>
import { list, save } from "@/api/business/consult";
import { listConsultResult } from "@/api/business/consultResult";
import useUserStore from '@/store/modules/user'
import {getListByUserId} from '@/api/system/role'
const { proxy } = getCurrentInstance();

/** 咨询查询对象 */
const webHost = import.meta.env.VITE_APP_BASE_API
const hostUrl = import.meta.env.VITE_HOST_URL
const queryParams = ref({
  isProcessInspection: "",
  lotCode: "",
  productDescription: "",
  consultDepart:"",
  content: "",
  pageNum: 1,
  pageSize: 10,
  status:'0'
});
/** 咨询变量 */
const dataList = ref([]);
const technicianController = ref(false)
const qualityController = ref(false)
const loading = ref(false);
const resultList = ref([])
const ids = ref([]);
const total = ref(0);

/***********************  方法区  ***********************/
//当前登录人员的咨询部门权限
function getLoginPower() {
  getResultList()
  if(useUserStore().user.userId == 1) {
    queryParams.value.consultDepartment =""
    technicianController.value = true
    qualityController.value = true
    getList()
  }else{
  getListByUserId({userId:useUserStore().user.userId}).then(res =>{
    let roleNames = res.data.map(item =>item.roleKey)
    technicianController.value = false
    qualityController.value = false
    console.log(roleNames)
    if(roleNames.includes("technician") && roleNames.includes("quality_control_officer")) {
      technicianController.value = true
      qualityController.value = true
     let index = roleNames.findIndex(item =>item == 'technicanResponser')
      if(res.data[index].perms.findIndex(item =>item == 'business:consult:list') >-1) {
        //能看到所有技术员的咨询
        queryParams.value.flag = true
      }else{
        queryParams.value.flag = false
      }
      queryParams.value.consultDepartment ="-1"
      getList()
    }else{
    //技术
        if(roleNames.includes('technician') && !roleNames.includes("quality_control_officer") ) {
      technicianController.value = true
     let index = roleNames.findIndex(item =>item == 'technicanResponser')
      if(res.data[index].perms.findIndex(item =>item == 'business:consult:list') >-1) {
        //能看到所有技术员的咨询
        queryParams.value.flag = true
      }else{
        queryParams.value.flag = false
      }
      queryParams.value.consultDepartment ="0"
      getList()
    }
    //品管
    if(!roleNames.includes('technician') && roleNames.includes("quality_control_officer")) {
      qualityController.value = true
      queryParams.value.consultDepartment ="1"
      getList()
    }
  }
  })
}
}
function handleChangeStatus(data){
  console.log(data)
  if(data.consultResultId != 0){
    let result = resultList.value.filter(item => item.value == data.consultResultId)
    console.log(result)
    data.consultResultResult = result[0].label
    data.status = result[0].status == 0?'2':'1'
  }else{
    data.consultResultResult = ""
    data.status = '0'
  }
  console.log(data)

  save({id:data.id,status:data.status,consultResultId:data.consultResultId,consultResultResult:data.consultResultResult}).then(res =>{
      proxy.$modal.msgSuccess("操作成功");
      getList()
  })
  
}
//查询咨询管理列表
function getResultList(){
  listConsultResult().then(res =>{
    res.rows.push({id:'0',result:"请选择"})
    resultList.value = res.rows.map(v => {
  return { value: v.id, label: v.result,status:v.status };
});
console.log(resultList.value)
  })
  
}
/** 查询咨询管理列表 */
function getList() {
  loading.value = true;
  list(queryParams.value).then((res) => {
    processImageUrl(res.rows)
    dataList.value = res.rows.map(v=>{return {...v,consultResultId:v.consultResultId+''}});
    console.log(dataList.value)
    console.log(dataList.value)
    total.value = res.total;
    loading.value = false;
  });
}
/** 咨询搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
function processImageUrl(data) {
      console.log('processImageUrl')
      for (var i = 0; i < data.length; i++) {
        var item = data[i]
          var urlList = previewImageUrl(item.pictureList)
          item.pictureList = urlList
      }
    }
function previewImageUrl(list) {
      var urlList = []
      if (list) {
        var picList = JSON.parse(JSON.stringify(list))

        for (var i = 0; i < picList.length; i++) {
          var item = picList[i]
          var url = document.location.origin + webHost + item.url
          urlList.push(url)
        }
      }
      return urlList
    }

const handleSetStatus = (type, data) => {
  const msg = type === "OK" ? "合格" : "不合格";
  proxy.$modal.confirm("确定" + msg + "？").then(() => {
    data.status = type === "OK" ? 2 : 1
    console.log(data)
    save({id:data.id,status:data.status}).then((res) => {
      if (res.code === 200) {
        getList();
        proxy.$modal.msgSuccess("操作成功");
      } else {
        proxy.$modal.msgSuccess("操作失败");
      }
    });
  });
};

onMounted(() => {
  getLoginPower();
});
</script>
