<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="验收结果" prop="checkResult">
        <el-select v-model="queryParams.checkResult" placeholder="请选择验收结果" clearable>
          <el-option v-for="dict in project_checking_result" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="技术专员" prop="technicianUserName">
        <el-select v-model="queryParams.technicianUserName" placeholder="请选择技术专员" clearable style="width:150px">
          <el-option v-for="item in technicianUserOptions" :key="item.userPhone" :label="item.userName"
            :value="item.userPhone">
            <span style="float: left">{{ item.userName }}</span>
            <span style="
                  float: right;
                  color: var(--el-text-color-secondary);
                  font-size: 13px;
                ">
              {{ item.userPhone }}
            </span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="监理专员" prop="superviseUserName">
         <el-select v-model="queryParams.superviseUserName" placeholder="请选择监理专员" style="width: 150px">
            <el-option v-for="item in superviseUserOptions" :key="item.userPhone" :label="item.userName"
              :value="item.userPhone">
              <span style="float: left">{{ item.userName }}</span>
              <span style="
                  float: right;
                  color: var(--el-text-color-secondary);
                  font-size: 13px;
                ">
                {{ item.userPhone }}
              </span>
            </el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="验收时间" prop="checkingDate">
        <el-date-picker clearable v-model="queryParams.checkingDate" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择验收时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd"
          v-hasPermi="['manage:projectChecked:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['manage:projectChecked:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['manage:projectChecked:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['manage:projectChecked:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="projectCheckedList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="项目名称" align="center" prop="projectName" v-if="false" />
      <el-table-column label="验收图片" align="center" prop="imageUrls" width="100">
        <template #default="scope">
          <div v-if="scope.row.imageUrls != null">
            <image-preview v-if="scope.row.imageUrls.split(',').length == 1" :src="scope.row.imageUrls" :width="50"
              :height="50" />
            <el-badge v-if="scope.row.imageUrls.split(',').length > 1" :value="scope.row.imageUrls.split(',').length"
              type="primary" class="item">
              <image-preview :src="scope.row.imageUrls" :width="50" :height="50" />
            </el-badge>
          </div>
          <div v-else style="color: var(--el-color-info-light-3)">暂 无 图 片</div>
        </template>
      </el-table-column>
      <el-table-column label="工序部位" align="center" prop="workingPositionFull" />
      <el-table-column label="验收描述" align="center" prop="intro" />
      <el-table-column label="班组长" align="center">
        <template #default="scope">
          <div>{{ scope.row.groupDeptUserName }}</div>
          <div>{{ scope.row.groupDeptUser }}</div>
        </template>
      </el-table-column>
      <el-table-column label="技术员" align="center">
        <template #default="scope">
          <div>{{ scope.row.technicianUserName }}</div>
          <div>{{ scope.row.technicianUser }}</div>
        </template>
      </el-table-column>
      <el-table-column label="监理专员" align="center">
        <template #default="scope">
          <div>{{ scope.row.superviseUserName }}</div>
          <div>{{ scope.row.superviseUser }}</div>
        </template>
      </el-table-column>
      <el-table-column label="验收时间" align="center" prop="checkingDate" width="120">
        <template #default="scope">
          <span>{{ parseTime(scope.row.checkingDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="验收结果" align="center" prop="checkResult">
        <template #default="scope">
          <dict-tag :options="project_checking_result" :value="scope.row.checkResult" />
        </template>
      </el-table-column>
      <el-table-column label="三方验收照" align="center" prop="checkingFiles" width="88">
        <template #default="scope">
          <div v-if="scope.row.checkingFiles != null">
            <image-preview v-if="scope.row.checkingFiles.split(',').length == 1" :src="scope.row.checkingFiles"
              :width="50" :height="50" />
            <el-badge v-if="scope.row.checkingFiles.split(',').length > 1"
              :value="scope.row.checkingFiles.split(',').length" type="primary" class="item">
              <image-preview :src="scope.row.checkingFiles" :width="50" :height="50" />
            </el-badge>
          </div>
          <div v-else style="color: var(--el-color-info-light-3)">暂 无 图 片</div>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="approveStatus">
        <template #default="scope">
          <dict-tag :options="project_check_status" :value="scope.row.appStatus" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:projectChecked:edit']" v-if="scope.row.approveStatus==100">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['manage:projectChecked:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改项目举牌验收对话框 -->
    <el-dialog :title="title" v-model="open" width="680px" append-to-body>
      <el-form ref="projectCheckedRef" :model="form" :rules="rules" label-width="88px">
        <el-form-item label="项目名称" v-if="form.projectId">
          <el-tag effect="plain">{{ form.projectName }}</el-tag>
        </el-form-item>
        <el-form-item label="验收图片" prop="imageUrls">
          <image-upload v-model="form.imageUrls" :limit="3" />
        </el-form-item>
        <el-form-item label="工序部位" prop="workingPosition">
          <el-tree-select ref="selTreePlan" v-model="form.workingPositionName" :data="planOptions"
            :props="{ value: 'id', label: 'taskName', children: 'children' }" value-key="id" placeholder="请选择工程计划名称"
            style="width: 100%" >
            <template #default="{ data }">
              {{ data.taskName }}<span style="float: right; color: var(--el-text-color-secondary); font-weight: 600">{{
                data.scheduleNode }} % </span>
            </template>
          </el-tree-select>
        </el-form-item>
        <el-form-item label="验收描述" prop="intro">
          <el-input v-model="form.intro" type="textarea" placeholder="请输入验收描述" />
        </el-form-item>
        <el-form-item label="班组长" prop="groupDeptUser">
          <el-select v-model="form.groupDeptUser" placeholder="请选择班组长" style="width: 100%">
            <el-option v-for="item in groupUserOptions" :key="item.userPhone" :label="item.userName"
              :value="item.userPhone">
              <span style="float: left">{{ item.userName }}</span>
              <span style="
                  float: right;
                  color: var(--el-text-color-secondary);
                  font-size: 13px;
                ">
                {{ item.userPhone }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="技术专员" prop="technicianUser">
          <el-select v-model="form.technicianUser" placeholder="请选择技术专员" style="width: 100%">
            <el-option v-for="item in technicianUserOptions" :key="item.userPhone" :label="item.userName"
              :value="item.userPhone">
              <span style="float: left">{{ item.userName }}</span>
              <span style="
                  float: right;
                  color: var(--el-text-color-secondary);
                  font-size: 13px;
                ">
                {{ item.userPhone }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="监理专员" prop="superviseUser">
          <el-select v-model="form.superviseUser" placeholder="请选择监理专员" style="width: 100%">
            <el-option v-for="item in superviseUserOptions" :key="item.userPhone" :label="item.userName"
              :value="item.userPhone">
              <span style="float: left">{{ item.userName }}</span>
              <span style="
                  float: right;
                  color: var(--el-text-color-secondary);
                  font-size: 13px;
                ">
                {{ item.userPhone }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="验收时间" prop="checkingDate">
          <el-date-picker v-model="form.checkingDate" type="date" style="width:100%" value-format="YYYY-MM-DD"
            placeholder="请选择验收时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="三方验收照" prop="checkingFiles">
          <image-upload v-model="form.checkingFiles" :limit="1" />
        </el-form-item>
        <el-form-item label="验收结果" prop="checkResult">
          <el-select v-model="form.checkResult" placeholder="请选择验收结果" style="width:100%">
            <el-option v-for="dict in project_checking_result" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ProjectChecked">
import { fileAllUsers } from '@/api/manage/proProjectInfoSubdeptsUsers'
import { listProjectChecked, getProjectChecked, delProjectChecked, addProjectChecked, updateProjectChecked, findCheckAllPlanDatas } from "@/api/manage/projectChecked";
import { listProProjectInfoSubdeptsUsers } from '@/api/manage/proProjectInfoSubdeptsUsers'
import useUserStore from "@/store/modules/user";

const { proxy } = getCurrentInstance();
const { project_checking_result, project_check_status, sys_is_del } = proxy.useDict('project_checking_result', 'project_check_status', 'sys_is_del');
const userStore = useUserStore();
const projectCheckedList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const planOptions = ref([]);
const groupUserOptions = ref([]);
const technicianUserOptions = ref([]);
const superviseUserOptions = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    checkResult: null,
    technicianUserName: '',
    superviseUserName: '',
    checkingDate: null
  },
  rules: {
    projectId: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
    imageUrls: [{ required: true, message: "验收图片不能为空", trigger: "change" }],
    workingPositionName: [{ required: true, message: "工序部位不能为空", trigger: "change" }],
    intro: [{ required: true, message: "验收描述不能为空", trigger: "blur" }],
    groupDeptUser: [{ required: true, message: "班组长不能为空", trigger: "change" }],
    technicianUser: [{ required: true, message: "技术专员不能为空", trigger: "change" }],
    superviseUser: [{ required: true, message: "监理专员不能为空", trigger: "change" }],
    checkingDate: [{ required: true, message: "验收时间不能为空", trigger: "change" }],
    checkingFiles: [{ required: true, message: "三方验收照不能为空", trigger: "change" }],
    checkResult: [{ required: true, message: "验收结果不能为空", trigger: "change" }]
  }
});

const { queryParams, form, rules } = toRefs(data);


/** 查询项目举牌验收列表 */
function getList() {
  loading.value = true;
  listProjectChecked(queryParams.value).then(response => {
    projectCheckedList.value = (response.rows||[]).map(item=>{
     item.appStatus=(item.checkResult==1 && (item.approveStatus==100 || item.approveStatus==4))?4: item.approveStatus
     let taskInfo=proxy.$tryToJson(item.workingPosition,null);
     item.workingPositionName=taskInfo.name||item.workingPosition;
     item.workingPositionFull=taskInfo.full||item.workingPosition;
     item.taskId=taskInfo.id;
      return item;
    });
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    comId: null,
    projectId: null,
    checkType: null,
    mainImage: null,
    imageUrls: null,
    workingPosition: null,
    workingPositionType: null,
    checkingNum: null,
    checkResult: null,
    intro: null,
    technicianUser: null,
    technicianUserName: null,
    superviseUser: null,
    superviseUserName: null,
    groupDeptUser: null,
    groupDeptUserName: null,
    checkingDate: null,
    checkingFiles: null,
    isDel: null,
    approveStatus: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("projectCheckedRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  if (!userStore.currentComId) {
    proxy.$modal.msgWarning("请切换到项目数据！！！");
    open.value = false;
    return false;
  }
  reset();
  open.value = true;
  form.value.comId = userStore.currentComId;
  form.value.comName = userStore.currentComName;
  form.value.projectId = userStore.currentPrjId;
  form.value.projectName = userStore.currentProName;
  title.value = "添加项目举牌验收";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getProjectChecked(_id).then(response => {
    let item= response.data;
    let task=proxy.$tryToJson(item.workingPosition,null);
    item.workingPositionName=task.name;
    item.workingPositionFull=task.full;
    item.taskId=task.id;
    setTimeout(()=>{
      proxy.$refs["selTreePlan"].setCurrentKey(task.id);
    },1000)
    form.value =item
    open.value = true;
    title.value = "修改项目举牌验收";
  });
}

/** 提交按钮 */
function submitForm() {
  
  proxy.$refs["projectCheckedRef"].validate(valid => {
    if (valid) {
      if (form.value.groupDeptUser) {
        groupUserOptions.value.forEach(item => {
          if (item.userPhone == form.value.groupDeptUser) {
            form.value.groupDeptUserName = item.userName;
          }
        });
      }
      if (form.value.technicianUser) {
        technicianUserOptions.value.forEach(item => {
          if (item.userPhone == form.value.technicianUser) {
            form.value.technicianUserName = item.userName;
          }
        });
      }
      if (form.value.superviseUser) {
        superviseUserOptions.value.forEach(item => {
          if (item.userPhone == form.value.superviseUser) {
            form.value.superviseUserName = item.userName;
          }
        });
      }
      let task=proxy.$refs["selTreePlan"].getCurrentNode();
      let taskInfo={
        id:task.id,
        name:task.taskName,
        full:task.fullPath,
      };
      form.value.workingPosition=JSON.stringify(taskInfo);
      if (form.value.id != null) {
        updateProjectChecked(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        form.value.approveStatus = "100";
        addProjectChecked(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除项目举牌验收编号为"' + _ids + '"的数据项？').then(function () {
    return delProjectChecked(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/projectChecked/export', {
    ...queryParams.value
  }, `projectChecked_${new Date().getTime()}.xlsx`)
}

function buildTree(all, id,path) {
  let tmps = all.filter((d) => d.parentId == id);
  if (tmps.length > 0) {
    tmps.forEach((it) => {
      it.fullPath = path ? path + "/" + it.taskName : it.taskName;
      it.children = buildTree(all, it.taskId,it.fullPath);
    });
  }
  return tmps;
}

/** 初始化计划管理 */
function initPlanDatas() {
  if (userStore.currentPrjId) {
    findCheckAllPlanDatas(userStore.currentPrjId).then((res) => {
      let treeDatas = buildTree(res.data, 1,"");
      planOptions.value = treeDatas;
    });
  }
}

function checkSysRole(user,role){
  let tmp=user.sysRoles;
  if(!tmp){
    return false;
  }
  let tmps=tmp.split(",");
  return tmps.find(it=>it.indexOf(role)==0);
}

function initUserOptions() {
  if (userStore.currentPrjId) {
    listProProjectInfoSubdeptsUsers({ projectId: userStore.currentPrjId, pageNum: 1, pageSize: 1000 }).then((res) => {
      let _groupUserOptions = [];
      let _technicianUserOptions = [];
      let _superviseUserOptions = [];
      let users = res.rows || [];
      users.forEach(item => {
        if (item.userPost == '3') {
          _groupUserOptions.push(item);
        } else if (checkSysRole(item,'zbjsy_')) {
          _technicianUserOptions.push(item);
        } else if (item.userPost == '71') {
          _superviseUserOptions.push(item);
        }
      });
      groupUserOptions.value = _groupUserOptions;
      technicianUserOptions.value = _technicianUserOptions;
      superviseUserOptions.value = _superviseUserOptions;
    });
  }
}

getList();
initPlanDatas();
initUserOptions();
</script>
