<template>
  <el-dialog :title="title" v-model="open" width="1100px" append-to-body>
    <div class="contentWrap" v-loading="loading">
      <el-form ref="checkFormRef" :model="form" :rules="rules" scroll-to-error
        :scroll-into-view-options="{ block: 'center' }" label-width="9em">
        <el-card header="基本信息" style="margin-bottom: 10px;" v-card-expand="{ isExpanded: true }">
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="任务编号" prop="taskCode">
                <el-input :disabled="disabled" v-model="form.taskCode" :placeholder="disabled ? '-' : '请输入任务编号'"
                  maxlength="30" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="检查人" prop="checkerName">
                <el-input :disabled="disabled" v-model="form.checkerName" :placeholder="disabled ? '-' : '请输入检查人'" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="被检查人/主管/班组" prop="checkedDepartmentName">
                <el-input v-if="form.checkedLevel === 'DEPARTMENT_LEVEL'" :disabled="disabled"
                  :value="form.checkedDepartmentName" :placeholder="disabled ? '-' : '请输入被检查人/主管/班组'" />
                <el-input v-else-if="form.checkedLevel === 'TEAM_LEVEL'" :disabled="disabled"
                  :value="form.checkedTeamName" :placeholder="disabled ? '-' : '请输入被检查人/主管/班组'" />
                <el-input v-else-if="form.checkedLevel === 'PERSONNEL_LEVEL'" :disabled="disabled"
                  :value="form.checkedPersonnelName" :placeholder="disabled ? '-' : '请输入被检查人/主管/班组'" />
                <el-input v-else-if="form.checkedLevel === 'BRIGADE_LEVEL'" :disabled="disabled"
                  :value="form.checkedBrigadeName" :placeholder="disabled ? '-' : '请输入被检查人/主管/班组'" />
                <el-input :disabled="disabled" v-else />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="检查地点" prop="nickName">
                <el-input :disabled="disabled" :value="viewText(form.terminlName, form.regionalName, form.channelName)"
                  :placeholder="disabled ? '-' : '请输入检查地点'" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="检查时间" prop="checkTime">
                <el-input :disabled="disabled" v-model="form.checkTime" :placeholder="disabled ? '-' : '请输入检查时间'" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>

        <el-card header="待整改任务" style="margin-bottom: 10px;" v-card-expand="{ isExpanded: true }">
          <div>
            <el-row :gutter="16">
              <el-col :span="24" v-for="item of groupHandler(form.checkProjectItemList)" :key="item.id"
                style="margin-bottom: 15px;">
                <div class="title">{{ item.title }}</div>
                <div v-for="attr in item.list" :key="attr.index" style="padding: 0 30px; box-sizing: border-box;">
                  <el-form-item :label="attr.projectName" label-width="auto"
                    :prop="`checkProjectItemList.${attr.index}.scoreLevel`">
                    <el-switch :disabled="disabled" v-model="attr.scoreLevel" active-value="QUALIFIED"
                      inactive-value="UNQUALIFIED" inline-prompt active-text="符合" inactive-text="不符合"
                      style="--el-switch-on-color: rgb(98, 111, 240); --el-switch-off-color: #ff4949" />
                  </el-form-item>
                  <div v-if="attr.scoreLevel === 'UNQUALIFIED'" style="padding: 0 30px; box-sizing: border-box;">
                    <el-form-item v-if="attr.checkUserList && attr.checkUserList.length" label="不合格人员" label-width="6em"
                      prop="checkedPersonnelName">
                      <el-input :disabled="disabled" :value="getUserName(attr.checkUserList)" />
                    </el-form-item>
                    <el-form-item v-if="attr.problemDescription" label="问题描述" label-width="6em"
                      :prop="`checkProjectItemList.${attr.index}.problemDescription`">
                      <el-input type="textarea" :disabled="disabled" v-model="attr.problemDescription" />
                    </el-form-item>
                  </div>
                </div>
              </el-col>
              <el-col :span="24" v-if="form.checkRecordBaseAttachmentList && form.checkRecordBaseAttachmentList.length">
                <div class="title">不合格照片</div>
                <div class="imgList">
                  <ImageUpload :modelValue="transformImglistData(form.checkRecordBaseAttachmentList)"
                    :disabled="disabled" />
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>

        <el-card header="整改要求" style="margin-bottom: 10px;" v-card-expand="{ isExpanded: true }">
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="负责人" prop="responsibleUserName">
                <el-input v-model="form.responsibleUserName" :disabled="disabled"
                  :placeholder="disabled ? '-' : '请输入负责人'" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="整改期限" prop="rectificationDeadline">
                <el-input v-model="form.rectificationDeadline" :disabled="disabled"
                  :placeholder="disabled ? '-' : '请输入整改期限'" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="整改要求" prop="rectificationSuggestions">
                <el-input type="textarea" v-model="form.rectificationSuggestions" :disabled="disabled"
                  :placeholder="disabled ? '-' : '请输入整改要求'" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-card>
        <el-card header="整改详情" style="margin-bottom: 10px;" v-card-expand="{ isExpanded: true }">
          <el-row :gutter="16">
            <el-col :span="24">
              <el-form-item label="整改详情" label-width="6em" prop="rectificationDetails">
                <el-input type="textarea" v-model="form.rectificationDetails" :disabled="disabled"
                  :placeholder="'请输入整改要求'" />
              </el-form-item>
            </el-col>
            <el-col :span="24" v-if="baseAttachmentList.length">
              <div class="title">整改图片</div>
              <div class="imgList">
                <ImageUpload v-model="baseAttachmentList" :disabled="disabled" />
              </div>
            </el-col>
          </el-row>
        </el-card>
        <el-card header="审批历史" style="margin-bottom: 10px;" v-card-expand="{ isExpanded: true }">
          <el-table :data="historyInstanceList">
            <el-table-column label="审批人" align="center" prop="operatorName" width="180" />
            <el-table-column label="审批时间" align="center" prop="operationTime" />
            <el-table-column label="审批状态" align="center" prop="comment" />
          </el-table>
        </el-card>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { watch, ref, onMounted, reactive, onUnmounted, computed } from 'vue'
import { getCheckCorrection, historyInstance } from "@/api/check/checkCorrection"
import { listUser } from "@/api/system/user"
const props = defineProps({
  id: {
    type: Number
  }
})

const disabled = ref(true)
const open = defineModel('show', ref(false))
const title = ref('整改单详情')
const form = ref({
  checkRecordBaseAttachmentList: [],
  baseAttachmentList: []
})
const loading = ref(false)
const historyInstanceList = ref([])
const listUserOption = ref([])
const checkFormRef = ref(null)
const getDetailInfo = () => {
  loading.value = true
  getCheckCorrection(props.id).then(res => {
    checkFormRef.value.resetFields()
    form.value = res.data
    if (res.data.instanceId) {
      return historyInstance(res.data.instanceId).then(res => {
        historyInstanceList.value = res.rows
        return
      })
    } else {
      return historyInstanceList.value = []
    }

  }).finally(() => {
    loading.value = false
  })
}

const viewText = (...rest) => {
  if (Array.isArray(rest) && rest.length) {
    return rest.reduce((cur, acc) => {
      if (acc) {
        cur += cur ? `/${acc}` : acc
      }
      return cur
    }, '')
  }
  return '-'
}

const transformImglistData = (imgList) => {
  if (Array.isArray(imgList) && imgList.length) {
    return imgList.map(item => {
      return {
        ...item,
        name: item.attachmentName,
        url: item.attachmentUrl,
      }
    })
  }
  return []
}

const baseAttachmentList = computed({
  get() {
    return transformImglistData(form.value.baseAttachmentList)
  },
  set(newValue) {
    form.value.baseAttachmentList = newValue.map(item => {
      return {
        attachmentName: item.name,
        attachmentUrl: item.url
      }
    })
  }
})

const groupHandler = (list) => {
  if (Array.isArray(list) && list.length) {
    return list.reduce((cur, acc, index) => {
      const findIndex = cur.findIndex(item => item.categoryCodeOne === acc.categoryCodeOne && item.categoryCodeTwo === acc.categoryCodeTwo)
      if (findIndex >= 0) {
        cur[findIndex].list.push({ index, ...acc })
      } else {
        cur.push({
          title: `${acc.categoryNameOne}/${acc.categoryNameTwo}`,
          categoryCodeOne: acc.categoryCodeOne,
          categoryCodeTwo: acc.categoryCodeTwo,
          list: [{ index, ...acc }]
        })
      }
      return cur
    }, [])
  }
  return []
}
const getUserInfo = () => {
  listUser().then(res => {
    listUserOption.value = res.rows.map((item) => ({
      value: item.userId,
      label: item.nickName
    }))
  })
}

const getUserName = (list) => {
  let res = ''
  if (Array.isArray(list) && list.length) {
    res = list.map(attr => {
      return (listUserOption.value.find(item => item.value === attr.userId) || {}).label
    }).filter(Boolean).join('、')
  }
  
  if (res) {
    return res
  } else {
    res = list.map((item) => item.userName).join('、')
    return res || '-'
  }

}

const cancel = () => {
  checkFormRef.value && checkFormRef.value.resetFields()
  form.value = {}
  open.value = false
}

watch(() => open.value, () => {
  if (open.value) {
    getDetailInfo()
  } else {
    form.value = {}
  }
})

const rules = reactive({
  rectificationDetails: [{ required: true, message: "请输入整改详情", trigger: "blur" }]
})

onMounted(() => {
  getUserInfo()
})
onUnmounted(() => {
  cancel()
})
</script>

<style lang="less" scoped>
.contentWrap {
  height: 75vh;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 0 10px;
}

:deep(.el-card) {
  .el-card__header {
    font-weight: 600;
    font-size: 16px;
    color: #000;
  }
}

.title {
  font-weight: 600;
  color: #000;
  margin-bottom: 10px;
}

.imgList {
  display: flex;
  flex-wrap: wrap;
  row-gap: 15px;
  column-gap: 15px;

  .img-item {
    width: 220px;
    height: 120px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    padding: 2px;
    box-sizing: border-box;

    img {
      width: 100%;
      height: 100%;
      object-fit: contain;
      border: none;
      outline: none;
    }
  }
}
</style>