<!--
  Description: 现场管理新增或编辑
  Author: 李亚光
  Date: 2023-04-24
 -->
<script lang="ts" setup name="sceneEdit">
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox, ElTable } from 'element-plus'
import addOperatives from './components/personTable.vue'
import personList from './components/personListDialog.vue'
import deviceList from './components/deviceListDialog.vue'
import { addScene, getSceneDetail, updateScene } from '@/api/scene'
const $route = useRoute()
const $router = useRouter()
const ruleFormRef = ref<FormInstance>() // from组件
const ruleForm: { [key: string]: string | any } = ref({
  workTitle: '', // 作业名称
  workRoad: '', // 所属道路
  workSiteDesc: '', // 作业描述
  workPerson: '', // 责任人
  workPersonName: '',
  workPersonPhoneNumber: '', // 负责人联系方式
  deviceList: [], // 	安全树列表
  workerList: [], // 人员列表
}) // 表单
const title = ref('')
const rules = ref({
  workTitle: [{ required: true, message: '作业名称不能为空', trigger: ['blur', 'change'] }],
  workRoad: [{ required: true, message: '所属道路不能为空', trigger: ['blur', 'change'] }],
  workSiteDesc: [{ required: true, message: '作业描述不能为空', trigger: ['blur', 'change'] }],
  workPersonName: [{ required: true, message: '责任人不能为空', trigger: ['blur', 'change'] }],
  deviceList: [{ required: true, message: '安全树列表不能为空', trigger: ['blur', 'change'] }],
  workerList: [{ required: true, message: '人员列表不能为空', trigger: ['blur', 'change'] }],
}) // 表单验证规则
// 人员列表弹窗组件
const selectPersonRef = ref()
// 选择负责人
const seletPerson = () => {
  selectPersonRef.value.initDialog()
}
// 确定负责人
const selectWorker = (row: any) => {
  ruleForm.value.workPerson = row.id
  ruleForm.value.workPersonName = row.workerName
  ruleFormRef.value?.clearValidate('workPersonName')
}
const selectDeviceRef = ref()
// 选择安全树设备
const seletDevice = () => {
  let id = ''
  if ($route.query.id as string) {
    id = $route.query.id as string
  }
  selectDeviceRef.value.initDialog('SafetyTree', id)
}
const safetyTree = ref()
// 确定安全树设备
const confirmDevice = (list: any) => {
  ruleForm.value.deviceList = []
  safetyTree.value = list
  list.forEach((device: any) => {
    ruleForm.value.deviceList.push(device.deviceCode)
  })
  ruleFormRef.value?.clearValidate('deviceList')
}
const personListRef = ref()
// 提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) { return }
  await formEl.validate((valid, _fields) => {
    if (valid) {
      ElMessageBox.confirm(
        '确认提交吗？',
        '提示',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        },
      ).then(() => {
        // 判断作业人员
        if (personListRef.value.userListData.length) {
          //  人员必须绑定安全设备
          if (personListRef.value.userListData.every((item: any) => item.braceletCode && item.hatCode && item.vastCode)) {
            console.log(safetyTree.value)
            ruleForm.value.deviceList = safetyTree.value.map((item: any) => ({ deviceId: item.id && item.deviceId ? item.deviceId : item.id }))
            ruleForm.value.workerList = personListRef.value.userListData.map((item: any) => ({ workerId: item.workerId, braceletCode: item.braceletCode, hatCode: item.hatCode, vastCode: item.vastCode }))
            // 新增编辑
            const id = $route.query.id as string
            if (id) {
              updateScene(ruleForm.value).then((res) => {
                if (res.code === 200) {
                  ElMessage.success('修改成功')
                  $router.go(-1)
                }
              }).catch((_error) => {
                ruleForm.value.deviceList = safetyTree.value.map((item: any) => (item.deviceCode))
              })
            }
            else {
              addScene(ruleForm.value).then((res) => {
                if (res.code === 200) {
                  ElMessage.success('新增成功')
                  $router.go(-1)
                }
              }).catch((_error) => {
                ruleForm.value.deviceList = safetyTree.value.map((item: any) => (item.deviceCode))
              })
            }
          }
          else {
            ElMessage.warning('所有作业人员需绑定安全设备')
          }
        }
        else {
          ElMessage.warning('请先添加作业人员')
        }
      })
    }
  })
}
// 取消
const resetForm = () => {
  $router.go(-1)
}
const userList = ref()
onMounted(() => {
  const id = $route.query.id as string
  title.value = '新增'
  if (id) {
    title.value = '编辑'
    // 获取详情
    getSceneDetail(id).then((res) => {
      const data = JSON.parse(JSON.stringify(res.data))
      ruleForm.value = data
      // 备份安全树
      safetyTree.value = data.deviceList
      // 展示安全树设备
      ruleForm.value.deviceList = data.deviceList.map((item: any) => item.deviceCode)
      // 备份人员列表
      userList.value = data.workerList
    })
  }
})
</script>

<template>
  <app-container style="overflow: hidden;">
    <!-- 选择负责人弹窗 -->
    <person-list ref="selectPersonRef" @add="selectWorker" />
    <!-- 选择安全树设备弹窗 -->
    <device-list ref="selectDeviceRef" :multiple="true" @add="confirmDevice" />
    <detail-page :title="`作业现场${title}`">
      <el-form
        ref="ruleFormRef" :model="ruleForm" :rules="rules" label-position="right" label-width="110px"
        :class="[title === '详情' ? 'isDetail' : '']" border stripe
      >
        <el-row :gutter="24">
          <el-col :span="2" />
          <el-col :span="8">
            <el-form-item label="作业名称" prop="workTitle" style="margin-top: 40px;">
              <el-input v-model.trim="ruleForm.workTitle" placeholder="作业名称" :disabled="title === '详情'" />
            </el-form-item>
            <el-form-item label="安全树" prop="deviceList" class="marg-item" style="margin-top: 40px;">
              <el-select
                v-model.trim="ruleForm.deviceList" placeholder="安全树" :disabled="title === '详情'"
                style="width: 100%;" multiple @focus="seletDevice"
              />
            </el-form-item>
            <el-form-item label="责任人" prop="workPersonName" style="margin-top: 40px;">
              <el-select
                v-model.trim="ruleForm.workPersonName" placeholder="责任人" :disabled="title === '详情'"
                style="width: 100%;" @focus="seletPerson"
              />
            </el-form-item>
          </el-col>
          <el-col :span="2" />
          <el-col :span="8">
            <el-form-item label="所属道路" prop="workRoad" style="margin-top: 40px;">
              <el-input v-model.trim="ruleForm.workRoad" placeholder="所属道路" :disabled="title === '详情'" />
            </el-form-item>
            <el-form-item label="作业概述" prop="workSiteDesc" style="margin-top: 40px;">
              <el-input
                v-model.trim="ruleForm.workSiteDesc" type="textarea" :rows="4" placeholder="作业概述"
                :disabled="title === '详情'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="24">
            <el-form-item label="" label-width="0px">
              <!-- 添加工作人员 -->
              <add-operatives ref="personListRef" style="width: 100%;" :list="userList" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="dialog-footer">
        <el-button style="margin-left: 30px;" @click="resetForm">
          取消
        </el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          保存
        </el-button>
      </div>
    </detail-page>
  </app-container>
</template>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-items: end;
  flex-direction: row-reverse;
}

:deep(.el-radio__label) {
  display: none;
}

:deep(.el-icon.avatar-uploader-icon) {
  font-size: 28px;
  color: #8c939d;
  width: 190px;
  height: 250px;
  text-align: center;
}

:deep(.avatar-uploader .avatar) {
  width: 190px;
  height: 250px;
  display: block;
}

.isDetail {
  ::v-deep {
    .el-form-item.is-required:not(.is-no-asterisk) .el-form-item__label-wrap > .el-form-item__label::before,
    .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label::before {
      display: none;
    }
  }
}
</style>

<style scoped>
.avatar-uploader .avatar {
  width: 190px;
  height: 250px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 190px;
  height: 250px;
  text-align: center;
}
</style>
