<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <el-form
      ref="basicFormRef"
      v-loading="formLoading"
      :model="formData"
      :rules="formRules"
      label-width="80px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="班组编码" prop="code">
            <el-input v-model="formData.code" placeholder="请输入班组编码" :disabled="isDisabled"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="班组名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入班组名称" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="班组类型" prop="teamGroup">
            <el-select v-model="formData.teamGroup" placeholder="请选择班组类型">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.BASIC_TEAM_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="负责人" prop="teamMonitorName">
            <div class="input-with-button">
              <el-input v-model="formData.teamMonitorName" placeholder="请选择负责人" disabled :style="{ width: '35%' }"/>
              <el-button :icon="Search" @click="addMonitor"/>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="车间代码" prop="workshopCode">
            <div class="input-with-button">
              <el-input v-model="formData.workshopCode" placeholder="请选择车间代码" disabled :style="{ width: '35%' }"/>
              <el-button :icon="Search" @click="addWorkShop"/>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产线代码" prop="productionLineCode">
            <div class="input-with-button">
            <el-input v-model="formData.productionLineCode" placeholder="请选择产线代码" disabled :style="{ width: '35%' }"/>
            <el-button :icon="Search" @click="addProductionLine"/>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="生效时间" prop="activeTime">
            <el-date-picker
              v-model="formData.activeTime"
              type="datetime"
              placeholder="请选择生效时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="x"
              style="width: 100%;"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="失效时间" prop="expireTime">
            <el-date-picker
              v-model="formData.expireTime"
              type="datetime"
              placeholder="请选择失效时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="x"
              style="width: 100%;"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="班组成员">
            <div class="tag-container flex gap-2">
              <el-tag v-for="ent in tags" :key="ent.username" closable :disable-transitions="false"
                      @close="handleClose(ent.username)">
                {{ ent.nickname}}
              </el-tag>
              <el-input
                v-if="inputVisible"
                ref="InputRef"
                v-model="inputValue"
                class="w-20"
                size="small"
              />
              <el-button v-else class="button-new-tag" size="small" @click="addUser">
                添加成员 +
              </el-button>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="是否可用" prop="available">
            <el-switch v-model="formData.available" active-value="TRUE" inactive-value="FALSE" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" placeholder="请输入内容" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>

<!--添加班组人员弹窗-->
  <SearchTable ref="searchTableRef" @searchTableSuccess="searchTableSuccess" />

</template>
<script lang="ts" setup>
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import * as TeamApi from '@/api/wms/team'
import request from "@/config/axios";
import { SearchTable } from '@/components/SearchTable'
import {searchUser} from "@/views/wms/basicDataManage/orderManage/team/team.data";
import * as UserApi from "@/api/system/user";
import {validateYS} from "@/utils/validator";
import { Search } from '@element-plus/icons-vue'
import * as WorkshopApi from "@/api/wms/workshop";
import {Workshop} from "@/views/wms/basicDataManage/factoryModeling/workshop/workshop.data";
import * as ProductionlineApi from '@/api/wms/productionline'
import { Productionline } from "@/views/wms/basicDataManage/factoryModeling/productionline/productionline.data";
import {ElInput} from "element-plus";

defineOptions({ name: 'TeamForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const tags=ref([])

const inputValue = ref('')
const inputVisible = ref(false)
const isDisabled = ref(false)
const InputRef = ref<InstanceType<typeof ElInput>>()

const formData = ref({
  code: '',
  name: '',
  teamGroup: '',
  available: 'TRUE',
  activeTime: '',
  expireTime: '',
  remark: '',
  createTime: '',
  members: '',
  workshopCode:'',
  workshopName:'',
  productionLineCode:'',
  productionLineName:'',
  teamMonitorCode:'',
  teamMonitorName:''
})
const formRules = reactive({
  code: [
    { required: true, message: '班组编码不能为空', trigger: 'blur' },
    { max: 50, message: '不得超过50个字符', trigger: 'blur' },
    { validator:validateYS, message: '请输入正确的代码', trigger: 'blur'}
  ],
  name: [
    { required: true, message: '班组名称不能为空', trigger: 'blur' },
    { max: 50, message: '不得超过50个字符', trigger: 'blur' }
  ],
  remark: [
    { max: 50, message: '不得超过50个字符', trigger: 'blur' }
  ],
  teamGroup: [{ required: true, message: '班组类别不能为空', trigger: 'change' }],
  workshopCode: [{ required: true, message: '请选择车间代码', trigger: 'blur' },],
  productionLineCode: [{ required: true, message: '请选择产线代码', trigger: 'blur' },],
  teamMonitorName: [{ required: true, message: '请选择负责人', trigger: 'blur' },],
})
const basicFormRef = ref() // 表单 Ref
const handleClose = (username: string) => {
  const index = tags.value.findIndex(tag => tag.username === username);
  if (index !== -1) {
    tags.value.splice(index, 1);
  }
}

/** 弹窗相关参数 */
const searchTableRef = ref();
const _searchTableTitle = ref();
const _searchTableAllSchemas = ref();
const _searchTablePage = ref();
const _formField = ref();
const _searchField = ref();
const _multiple = ref();
const _type = ref();
const _row = ref();
const _searchCondition = ref({})

const addMonitor = () =>{
  addUserCommon(false,'monitor')
}

const addUser = () =>{
  addUserCommon(true,'username')
}

/** 选择人员弹窗 */
const addUserCommon = (multiple,field) => {
  _searchCondition.value = {}
  const filters: any[] = []
  filters.push({
    action: "==",
    column: 'userType',
    value: 'WORKER'
  })
  // 参数整理
  _searchCondition.value.isSearch = true
  _searchCondition.value.filters = filters
  _searchTableTitle.value = '选择人员'
  _multiple.value = multiple
  _formField.value = field
  _searchField.value = field
  _searchTablePage.value = UserApi.getUserPage
  _searchTableAllSchemas.value = searchUser.allSchemas
  openCommon()
}

/** 选择车间弹窗 */
const addWorkShop = () => {
  _searchCondition.value = {}
  const filters: any[] = []
  filters.push({
    action: "==",
    column: 'available',
    value: 'TRUE'
  })
  // 参数整理
  _searchCondition.value.isSearch = true
  _searchCondition.value.filters = filters
  _searchTableTitle.value = '选择车间'
  _multiple.value = false
  _formField.value = 'workshop'
  _searchField.value = 'workshop'
  _searchTablePage.value = WorkshopApi.getWorkshopPage
  _searchTableAllSchemas.value = Workshop.allSchemas
  openCommon()
}

/** 选择产线弹窗 */
const addProductionLine = () => {
  if (formData.value.workshopCode == '' || formData.value.workshopCode == null ){
    message.warning('请先选择车间代码');
    return
  }
  _searchCondition.value = {}
  const filters: any[] = []
  filters.push({
    action: "==",
    column: 'available',
    value: 'TRUE'
  },{
    action: "==",
    column: 'workshopCode',
    value: formData.value.workshopCode
  })
  // 参数整理
  _searchCondition.value.isSearch = true
  _searchCondition.value.filters = filters
  _searchTableTitle.value = '选择产线'
  _multiple.value = false
  _formField.value = 'productionLine'
  _searchField.value = 'productionLine'
  _searchTablePage.value = ProductionlineApi.getProductionlinePage
  _searchTableAllSchemas.value = Productionline.allSchemas
  openCommon()
}

/** 弹窗选择之后  回调函数 */
const searchTableSuccess = (formField, searchField, val, formRef, type, row ) => {
  nextTick?.(() => {
    if (formField === 'workshop') {
      if (formData.value.workshopCode != val[0].code){
        formData.value.productionLineCode = null
        formData.value.productionLineName = null
      }
      formData.value.workshopCode = val[0].code
      formData.value.workshopName = val[0].name
    }
    else if (formField === 'productionLine'){
      formData.value.productionLineCode = val[0].code
      formData.value.productionLineName = val[0].name
    }
    else if (formField === 'monitor'){
      formData.value.teamMonitorCode = val[0].username
      formData.value.teamMonitorName = val[0].nickname
    }
    else {
      val.forEach(item => {
        const isExist = tags.value.some(tag => tag.username === item.username);
        if (!isExist){
          const newUser = {};
          if (formField === 'username') {
            newUser['username'] = item.username;
            newUser['nickname'] = item.nickname;
          }
          tags.value.push(newUser);
        }
      });
    }
  })
}
/*打开弹窗*/
const openCommon = () => {
  searchTableRef.value.open(
    _searchTableTitle.value,
    _searchTableAllSchemas.value,
    _searchTablePage.value,
    _formField.value,
    _searchField.value,
    _multiple.value,
    _type.value,
    _row.value,
    _searchCondition.value
  )
}
/** 初始化弹窗 */
const open = async (type: string, row?: object) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (row) {
    isDisabled.value = true;
    formLoading.value = true
    try {
       formData.value = await request.get({ url: `/wms/team/get?id=` + row.id });
      tags.value=JSON.parse(formData.value.members)
    } finally {
      formLoading.value = false
    }
  }
  else {
    isDisabled.value = false;
    tags.value=[];
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!basicFormRef) return
  const valid = await basicFormRef.value.validate()
  if (!valid) return
  if (tags.value.length > 15  ){
    message.warning('班组成员最多15人');
    return
  }
  // 提交请求
  formLoading.value = true
  formData.value.members = JSON.stringify(tags.value)
  try {
    const data = formData.value as unknown as TeamApi.TeamVO
    if (formType.value === 'create') {
      await TeamApi.createTeam(data)
      message.success(t('common.createSuccess'))
    } else {
      await TeamApi.updateTeam(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    code: '',
    name: '',
    teamGroup: '',
    available: 'TRUE',
    activeTime: '',
    expireTime: '',
    remark: '',
    createTime: '',
    members: '',
    workshopCode:'',
    workshopName:'',
    productionLineCode:'',
    productionLineName:'',
    teamMonitorCode:'',
    teamMonitorName:''
  }
  basicFormRef.value?.resetFields()
}

</script>

<style scoped>
.tag-container {
  margin-top: 10px; /* 可根据需要调整标签容器与表单项之间的间距 */
  border: 1px solid #ccc; /* 添加边框样式 */
  padding: 10px; /* 可根据需要调整容器内边距 */
  width: 950px; /* 设置固定宽度为 950px */
  overflow-y: auto; /* 当内容溢出容器高度时显示滚动条 */
  word-wrap: break-word; /* 使用 word-wrap 属性实现超出范围换行 */
  overflow-wrap: break-word; /* 兼容性更好的写法 */
  flex-wrap: wrap;
}
.input-with-button {
  display: flex;
  align-items: center;
  width: 100%;
}

.input-with-button > .el-input {
  flex: 1;
  /*margin-right: 10px;*/
}

</style>
