<template>
  <div class="app-container problemmodify-draft">
    <el-form :model="data.queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="检查类型" prop="problemType">
        <el-select v-model="data.queryParams.problemType" placeholder="请选择检查类型" clearable>
          <el-option v-for="dict in ssp_proble_type" :key="dict.value" :label="dict.label" :value="dict.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="整改人" prop="lordSent">
        <el-input v-model="data.queryParams.userName" style="width: 200px;" placeholder="请输入人员姓名/联系方式" clearable
          @keyup.enter="handleQuery" />
      </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 size="mini" @click="handleAdd"
          v-hasPermi="['trouble:smzSspProblemmodifyDraft:add']">
          <el-icon>
            <Plus />
          </el-icon>新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain size="mini" @click="dataSynchronization" :disabled="single"
          v-hasPermi="['trouble:smzSspProblemmodifyDraft:add']">
          <el-icon>
            <CopyDocument />
          </el-icon>
          数据同步</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-tooltip content="批量提交选择的数据！" placement="bottom">
          <el-button type="success" plain size="mini" @click="batchSubmitForm" :disabled="multiple"
            v-hasPermi="['trouble:smzSspProblemmodifyDraft:add']">
            <el-icon>
              <Check />
            </el-icon>批量提交</el-button>
        </el-tooltip>
      </el-col>

    </el-row>
    <el-alert title="操作说明" class="tips" effect="dark" type="warning" :closable="false">
      <template #title>
        <div><strong>数据同步:</strong>将选中行的数据同步到（当前项目或项目为空）的其它行！</div>
        <div><strong>批量提交:</strong>将选中行的数据，数据验证通过后一次全部提交！</div>
      </template>
    </el-alert>
    <el-form :model="data.form" :rules="data.rules" ref="formRef">
      <el-table :data="data.showList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="30" align="center" />
        <el-table-column type="index" width="50" align="center" label="序号">
        </el-table-column>

        <el-table-column align="center" width="180" class-name="td-up-img" label="问题图片">
          <template #default="scope"> 
            <div :class="scope.row.errSmarkUrl?'is-err':''"> 
            <image-upload v-model="scope.row.smarkUrl" previewAll :limit="5" :isShowTip="false"  @change="scope.row.errSmarkUrl=scope.row.smarkUrl?false:true"/>     
          </div>     
          </template>
        </el-table-column>
        <el-table-column align="center" width="180" class-name="td-proble-type" label="隐患类型">
          <template #default="scope">
            <div :class="scope.row.errProblemType?'is-err':''"> 
            <el-select v-model="scope.row.problemType" placeholder="请选择检查类型" clearable>
              <el-option v-for="dict in ssp_proble_type" :key="dict.value" :label="dict.label" :value="dict.value">
              </el-option>
            </el-select>
            </div>
            <el-select v-model="scope.row.dangerType" placeholder="请选择隐患类型" clearable style="margin-top:80px;">
              <el-option v-for="dict in ssp_proble_sub_type" :key="dict.value" :label="dict.label" :value="dict.value">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="施工部位" align="center" prop="workParts" min-width="240" class-name="td-textarea">
          <template #default="scope">
            
            <el-input v-model="scope.row.workParts" placeholder="请输入施工部位" type="textarea" :rows="3" />
          
          </template>
        </el-table-column>
        <el-table-column label="整改要求" align="center" prop="changeInfo" min-width="240" class-name="td-textarea">
          <template #default="scope">
            <el-input v-model="scope.row.changeInfo" placeholder="请输入整改要求" type="textarea" :rows="3" />
          </template>
        </el-table-column>
        <el-table-column label="问题人员" align="center" width="300" class-name="td-select">
          <template #default="scope">
            <el-form-item label="整改人">
              <el-select v-model="scope.row.lordSent" placeholder="请选择人员" clearable
                popper-class="select-popper-group-pd">
                <el-option-group v-for="group in data.modUserList" :key="group.label" :label="group.label">
                  <el-option v-for="item in group.options" :key="item.value" :label="item.label" :value="item.value" />
                </el-option-group>
              </el-select>
            </el-form-item>
            <el-form-item label="抄送人">
              <el-select v-model="scope.row.copySend" placeholder="请选择人员" clearable multiple collapse-tags
                popper-class="select-popper-group-pd" collapse-tags-tooltip>
                <el-option-group v-for="group in data.ccUserList" :key="group.label" :label="group.label">
                  <el-option v-for="item in group.options" :key="item.value" :label="item.label" :value="item.value" />
                </el-option-group>
              </el-select>
            </el-form-item>
            <el-form-item label="复检人">
              <el-select v-model="scope.row.recheckSend" placeholder="请选择人员" clearable
                popper-class="select-popper-group-pd" collapse-tags-tooltip>
                <el-option-group v-for="group in data.recheckUserList" :key="group.label" :label="group.label">
                  <el-option v-for="item in group.options" :key="item.value" :label="item.label" :value="item.value" />
                </el-option-group>
              </el-select>
            </el-form-item>
          </template>
        </el-table-column>

        <el-table-column label="整改截至时间" align="center" prop="nickedTime" width="150">
          <template #default="scope">
            <el-form-item label="">
              <el-date-picker v-model="scope.row.nickedTime" type="date" placeholder="选择日期" value-format="yyyy-MM-dd"
                style="width: 200px" />
            </el-form-item>
          </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="submitRow(scope.row)"
              v-hasPermi="['trouble:problemmodifyDraft:edit']">提交</el-button><br />
            <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
              v-hasPermi="['trouble:problemmodifyDraft:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
  </div>
</template>

<script setup name="ProblemmodifyDraft">
import {
  listProblemmodifyDraft,
  getProblemmodifyDraft,
  delProblemmodifyDraft,
  addProblemmodifyDraft,
  updateProblemmodifyDraft,
} from "@/api/trouble/problemmodifyDraft";
import useUserStore from '@/store/modules/user'
import { listProProjectInfoSubdeptsUsers } from "@/api/manage/proProjectInfoSubdeptsUsers";
const userStore = useUserStore()
const { proxy } = getCurrentInstance();
const { ssp_proble_type, ssp_proble_sub_type } = proxy.useDict('ssp_proble_type', 'ssp_proble_sub_type');

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 uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/file/upload"); // 上传文件服务器地址

const data = reactive({
  dataList: [],
  showList: [],
  form: {},
  queryParams: {
    problemType: null,
    userName: null
  },
  rules: {
   
  },
  selData: [],
  modUserList: [],//整改人
  ccUserList: [],//抄送人
  recheckUserList: [],//复检人  
});

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


/** 搜索按钮操作 */
function handleQuery() {
  debugger
  data.showList = data.dataList.filter(d => {
    let ck1 = true;
    if (data.queryParams.problemType) {
      ck1 = d.problemType == data.queryParams.problemType;
    }
    return ck1;
  });
}

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

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

/** 新增按钮操作 */
function handleAdd() {
  let row = {
    key: +new Date(),
    id: null,
    projectId: userStore.currentPrjId,
    comId: userStore.currentComId,
    problemType: null,
    dangerType: null,
    smarkUrl: null,
    workParts: null,
    changeInfo: null,
    lordSent: null,
    copySend: null,
    recheckSend: null,
    nickedTime: null,
    isDel: 0,
    infoType: 1
  }
  data.dataList.push(row);
  data.showList.push(row);
}
/** 数据同步 */
function dataSynchronization() {
  let row = data.selData[0];
  data.showList.forEach(it => {
    if (it != row) {
      it.problemType = row.problemType;
      it.dangerType = row.dangerType;
      it.smarkUrl = row.smarkUrl;
      it.workParts = row.workParts;
      it.changeInfo = row.changeInfo;
      it.lordSent = row.lordSent;
      it.copySend = row.copySend;
      it.recheckSend = row.recheckSend;
      it.nickedTime = row.nickedTime;
    }
  });
}
function submitRow(row) {
  debugger
  if (checkRow(row)) {

  }
}
function checkRow(row) {
  row.errSmarkUrl=false;
  row.errProblemType=false;
  if (!row.smarkUrl) {    
    row.errSmarkUrl=true;
    return false;
  }
  if (!row.problemType) {
    row.errProblemType=true;
    return false;
  }
  if (!row.dangerType ) {
    return false;
  }
  return true;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["problemmodifyDraftRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateProblemmodifyDraft(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addProblemmodifyDraft(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  if (data.dataList.length == 1) {
    proxy.$modal.msgError("至少保留一条数据");
    return;
  }
  proxy.$modal
    .confirm('是否确认删除数据项？')
    .then(function () {
      data.showList.splice(row, 1);
      data.dataList.splice(row, 1);
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "trouble/problemmodifyDraft/export",
    {
      ...queryParams.value,
    },
    `problemmodifyDraft_${new Date().getTime()}.xlsx`
  );
}
function makeSelectData(users, type) {
  let objs = {};
  users.forEach(it => {
    let deptName = it.subDeptName;
    if (!objs[deptName]) {
      objs[deptName] = [];
    }
    objs[deptName].push(it);
  })
  let arr = [];
  for (let k in objs) {
    arr.push({
      label: k,
      options: objs[k].map(it => {
        let pos = type ? `[${it.userPost == 2 ? '项目经理' : it.userPost == 3 ? '班组长' : ''}]` : ''
        return {
          value: it.userId,
          label: it.userName + pos,
          data: it
        }
      })
    })
  }
  console.log("--->", arr)
  return arr;
}
function getUserTree() {
  let row = {
    key: +new Date(),
    id: null,
    projectId: userStore.currentPrjId,
    comId: userStore.currentComId,
    problemType: null,
    dangerType: null,
    smarkUrl: null,
    workParts: null,
    changeInfo: null,
    lordSent: null,
    copySend: null,
    recheckSend: null,
    nickedTime: null,
    isDel: 0,
    infoType: 1
  };
  data.dataList.push(row)
  data.showList.push(row);
  listProProjectInfoSubdeptsUsers({ projectId: userStore.currentPrjId, pageNum: 1, pageSize: 1000 }).then(d => {
    let users = d.rows || [];
    data.modUserList = makeSelectData(users.filter(it => it.subDeptType == 4 || it.subDeptType == 5).filter(it => it.userPost == 2 || it.userPost == 3), true);
    data.ccUserList = makeSelectData(users.filter(it => it.userPost != 4 && it.userPost != 5));
    data.recheckUserList = makeSelectData(users.filter(it => it.subDeptType == 1));
  })
}
getUserTree();
</script>
<style lang="scss">
.problemmodify-draft {
  .td-up-img {
    .component-upload-image {
      height: 150px;
      overflow: hidden;

      .el-upload-list__item {
        position: absolute;
      }
    }
  }

  .td-textarea {
    .cell {
      width: 100%;
      height: 100%;

      .el-textarea {
        width: 100%;
        height: 150px;

        .el-textarea__inner {
          width: 100%;
          height: 100%;
        }
      }
    }
  }

  .td-select {    .el-select {
      width: 100%;
    }
  }
  .is-err{
    position: relative;
    padding-bottom:12px;
    .el-upload--picture-card{
      border-color: red;
    }
    &::after{
      content: "不为空";
      color: red;
      left: 0px;
      font-size:12px;
      position:absolute;
      bottom: -6px;
    }
  }
}

.select-popper-group-pd {
  .el-select-group {
    .el-select-dropdown__item {
      padding-left: 30px;
    }
  }
}
</style>