<template>
  <el-card class="hl-card" style="position: relative">
    <template #header>
      <span><span v-html="dialogTitle"></span>页</span>
    </template>
    <el-form ref="formRef" :model="formData" label-width="160px" v-loading="formLoading">
      <el-card class="hl-card-info">
        <template #header>
          <div class="hl-card-info-icona"></div><span class="hl-card-info-text">基础信息</span>
        </template>

        <el-row>
          <el-col :span="24">
            <el-row>

              <el-col :span="6">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="生产任务单号" prop="taskNo">
                      <el-input class="!w-265px" placeholder="系统自动生成" v-model="formData.taskNo" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="项目名称" prop="projectName">
                      <el-input class="!w-265px" placeholder="项目名称" v-model="formData.projectName" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="BOM清单号" prop="bomCode">
                      <el-input class="!w-265px" placeholder="" v-model="formData.bomCode" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="80">
                    <el-form-item label="子项目数量" prop="projectSubNum">
                      <el-input disabled v-model="formData.projectSubNum" show-word-limit  class="!w-265px"/>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>

              <el-col :span="6">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="生产计划单号" prop="planNo">
                      <el-input class="!w-265px" placeholder="生产计划单号" v-model="formData.planNo" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="项目结束日期" prop="projectEndTime">
                      <el-date-picker class="!w-265px" v-model="formData.projectEndTime" type="date" value-format="x" placeholder="项目结束日期" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="BOM版本号" prop="bomVersion">
                      <el-input class="!w-265px" placeholder="BOM版本号" v-model="formData.bomVersion" disabled>
                        <template #append v-if="refreshStatus == 1"><el-button @click="handleReFresh" style="background-color:var(--el-color-primary); color:#fff">
                            <Icon icon="ep:refresh"  />
                          </el-button></template>
                      </el-input>

                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="80">
                    <el-form-item label="备注" prop="description">
                      <el-input :disabled="detailDisabled" class="!w-713px" type="textarea" v-model="formData.description" show-word-limit maxlength="200" />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>

              <el-col :span="6">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="项目编号" prop="projectCode">
                      <el-input class="!w-265px" placeholder="项目编号" v-model="formData.projectCode" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="子项目名称" prop="projectSubName">
                      <el-input class="!w-265px" placeholder="子项目名称" v-model="formData.projectSubName" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="创建时间" prop="createTime">
                      <el-date-picker class="!w-265px" v-model="formData.createTime" type="date" value-format="x" placeholder="创建时间" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>

              <el-col :span="6">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="客户名称" prop="customerName">
                      <el-input class="!w-265px" v-model="formData.customerName" placeholder="客户名称" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="子项目编号" prop="projectSubCode">
                      <el-input class="!w-265px" v-model="formData.projectSubCode" placeholder="子项目编号" disabled />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="单据状态" prop="status">
                      <el-select v-model="formData.status" placeholder="单据状态" clearable class="!w-265px" disabled>
                        <el-option v-for="dict in getIntDictOptions(DICT_TYPE.HELI_BOM_STATUS)" :key="dict.value" :label="dict.label" :value="dict.value" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-col>

            </el-row>
          </el-col>
        </el-row>
      </el-card>

      <!-- 表格类信息 -->
      <el-card class="hl-card-info">
        <template #header>
          <div class="hl-card-info-icona"></div><span class="hl-card-info-text">任务明细</span>
        </template>
        <el-row>
          <el-col>
            <el-card class="hl-incard">
              <el-form ref="subFormRef" :model="formData.bomDetails" :rules="subFormRules" v-loading="formLoading" label-width="0" >
                <el-table :row-class-name="tableRowClassName" :data="formData.bomDetails"  >
                  <el-table-column label="序号" type="index" min-width="50px" />
                  <el-table-column label="变更次数" prop="bomEditStatus" max-width="60px" align="center">
                    <template #default="{ row}">
                        <el-text class="mx-1" max-width="60px">{{row.bomOperateCount==0?'无':'第'+row.bomOperateCount+'次'}}</el-text>
                    </template>
                  </el-table-column>
                  <!-- <el-table-column v-if="formData.bomStatus == 2|| formData.bomStatus == 7" style="text-align: center"  label="库存" prop="amount" min-width="150"> -->
                    <el-table-column
                    style="text-align: center"
                    label="变更履历"
                    max-width="70px"
                    :show-overflow-tooltip="true"
                  >
                    <template #header>
                      <span class="hl-table_header">*</span>变更履历
                    </template>
                    <template #default="{ row}">
                      <span class="memo-content">{{ row.memo }}</span>
                      <!-- <el-tooltip
                        class="box-item"
                        effect="dark"
                        placement="top-end"
                        :content="row.memo"
                      >
                        <el-button    link>备注</el-button> -->
                      <!-- </el-tooltip> -->
                    </template>
                  </el-table-column>
                  <el-table-column label="零件名称" prop="materialName" max-width="80px"/>
                  <el-table-column label="是否标准件" prop="typeName" max-width="100px" />
                  <el-table-column label="材质" prop="compositionName" max-width="80px"/>
                  <el-table-column label="规格型号" prop="spec" max-width="80px"/>
                  <el-table-column label="图号" prop="blueprintNo" max-width="50px"/>
                  <el-table-column label="数量" prop="amount" max-width="50px"/>

                  <el-table-column label="BOM状态" prop="bomEditStatus">
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.bomEditStatus`" class="mb-0px!">
                        <el-select class="!w-265px" v-model="row.bomEditStatus" disabled placeholder="下拉选择">
                          <el-option
                            v-for="dicts in heliBomStatusOptions" :key="dicts.value"
                            :label="dicts.label" :value="dicts.value" />
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column label="零件编码" prop="materialCode"  max-width="80px"/>
                  <el-table-column label="系统单位" prop="unit">
                    <template #header> <span class="hl-table_header">*</span>系统单位</template>
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.unit`" class="mb-0px!">
                        <span v-if="row.type == '1'">{{ getDictLabel(DICT_TYPE.HELI_MATERIAL_UNIT, row.unit) }}</span>
                        <el-select disabled v-else v-model="row.unit" clearable class="!w-250px">
                          <el-option v-for="dict in getStrDictOptions(DICT_TYPE.HELI_MATERIAL_UNIT)" :key="dict.value" :label="dict.label" :value="dict.value" />
                        </el-select>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column min-width="80px" align="center" fixed="right">
                    <template #header><span class="hl-table_header">*</span>负责人</template>
                    <template #default="{ row}">
                      <el-select :disabled="getDisable(row.bomEditStatus)" clearable filterable v-model="row.owner" placeholder="请选择负责人" style="width: 170px">
                      <el-option
                          v-for="item in ownerList"
                          :key="item.index"
                          :label="item.label"
                          :value="item.id"
                        />
                      </el-select>
                      <!-- <el-form-item :prop="`${$index}.owner`" class="mb-0px!" :rules="subFormRules.owner">
                        <UserSelect :disabled="detailDisabled" v-model="row.owner" @update:new-value="handleSelectedUser9($index, $event)" class="!w-265px" />
                      </el-form-item> -->
                    </template>
                  </el-table-column>
                  <el-table-column min-width="120px" align="center" fixed="right">
                    <template #header><span class="hl-table_header">*</span>需求完成日期</template>
                    <template #default="{ row, $index }">
                      <el-form-item :prop="`${$index}.requireEndDate`" class="mb-0px!" :rules="subFormRules.requireEndDate">
                        <el-date-picker :disabled="getDisable(row.bomEditStatus)" class="!w-265px" v-model="row.requireEndDate" type="date" value-format="x" placeholder="需求完成日期" />
                      </el-form-item>
                    </template>
                  </el-table-column>
                </el-table>
              </el-form>
            </el-card>
          </el-col>
        </el-row>
      </el-card>

      <el-card class="hl-card-info">
        <template #header>
          <div class="hl-card-info-icona"></div><span class="hl-card-info-text">操作日志</span>
        </template>
        <el-row>
          <el-col>
            <el-card class="hl-incard">
              <el-table :data="formData.operateLogs" class="hl-table" :style="{ height: formData.operateLogs.length > 10 ? '450px' : '' }">
                <el-table-column prop="type" label="操作" align="center" width="200px">
                  <template #default="scope">
                    {{ getDictLabel(DICT_TYPE.SYSTEM_OPERATE_TYPE, scope.row.type) }}
                  </template>
                </el-table-column>
                <el-table-column prop="userNickname" label="操作人" align="center" />
                <el-table-column label="操作时间" align="center" prop="startTime" width="220" :formatter="dateFormatter" />
              </el-table>
            </el-card>
          </el-col>
        </el-row>
      </el-card>
    </el-form>
    <div class="hl-footer text-center">
      <el-button @click="() => router.back()" size="large">取 消</el-button>
      <el-button v-if="pageType != 'detail' && formData.status == 1" @click="submitForm('SAVE')" type="primary" :disabled="formLoading" size="large">保 存</el-button>
      <el-button v-if="pageType != 'detail' && formData.status == 1" @click="submitForm('SUBMIT')" type="success" :disabled="formLoading" size="large">提 交</el-button>
      <el-button v-if="pageType != 'detail' && formData.status == 2" @click="submitForm('CANCEL_SUBMIT')" type="danger" :disabled="formLoading" size="large">取消提交</el-button>
    </div>
  </el-card>
</template>
<script setup lang="ts">
import { inject } from 'vue'
import { Search, Plus } from '@element-plus/icons-vue'
import { getIntDictOptions, getStrDictOptions, getDictLabel, DICT_TYPE } from '@/utils/dict'
import { betweenDay, formatDate, dateFormatter } from '@/utils/formatTime'
import { getOperateLogPage } from '@/api/system/operatelog'
import * as PlanTaskApi from '@/api/heli/plantask'
import * as PlanTaskBomApi from '@/api/heli/plantaskbom'
import UserSelect from '@/views/heli/hlvuestyle/userSelect.vue'
import * as TaskDispatchApi from '@/api/heli/taskdispatch'
import { get } from 'sortablejs'
const reload: any = inject('reload')

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

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formRef = ref() // 表单
const subFormRef = ref() //子表单 Ref
const formData = ref({
  id: undefined,
  active: undefined,
  projectId: undefined,
  projectPlanId: undefined,
  projectPlanSubId: undefined,
  processBomId: undefined,
  taskNo: undefined,
  planNo: undefined,
  projectCode: undefined,
  customerName: undefined,
  projectName: undefined,
  projectEndTime: undefined,
  projectSubCode: undefined,
  projectSubName: undefined,
  bomCode: undefined,
  bomVersion: undefined,
  createTime: undefined,
  description: undefined,
  status: undefined,
  operateLogs: [],
  bomDetails: []
})
const getDisable = (bomEditStatus)=>{
  if(bomEditStatus == 1){
    return true;
  }else{
  return detailDisabled.value
  }

}
const subFormRules = reactive({
  owner: [{ required: true, message: '负责人不能为空', trigger: 'blur' }],
  requireEndDate: [{ required: true, message: '要求完成日期不能为空', trigger: 'blur' }]
})
//接收物料传递的数据
const handleSelectedMaterial = (row: any, newValue: any) => {
  row.materialId = newValue.id
  row.materialName = newValue.name
  row.materialCode = newValue.code
  row.spec = newValue.spec
  row.unit = newValue.unit
}
const heliBomStatusOptions = ref<bomEditStatusEnum[]>([
  { value: 0, label: '初始' },
  { value: 1, label: '删除' },
  { value: 2, label: '新增' },
  { value: 3, label: '增补' },
  { value: 4, label: '修改' },
]);
const submitForm = async (operate) => {
  // 校验表单
  await subFormRef.value.validate()

  if (operate == 'SUBMIT' && formData.value.bomDetails.length == 0) {
    message.alertWarning('任务明细不能为空')
    return
  }

  // 提交请求
  formLoading.value = true
  try {
    formData.value.active = operate
    const data = formData.value as unknown as PlanTaskApi.PlanTaskVO
    data.status = operate == 'SUBMIT' ? 2 : 1
    await PlanTaskApi.updatePlanTask(data)

    message.success(t('common.updateSuccess'))
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
    reload()
  }
}

const handleReFresh = async () => {
  if(formData.value.status == 2){
    message.alertWarning('请先取消提交，再点击此按钮！')
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    await PlanTaskApi.refreshPlanTaskByPlanId(formData.value.projectPlanSubId)
  } finally {
    reload()
  }

  formLoading.value = false
}
const refreshStatus = ref()

const queryParams = reactive({
  pageNo: 1,
  pageSize: 99,
  taskId: undefined
})
type OwnerListType = {
  index: number;
  id: number;
  label: string;
};
const getOwnerListThis = async (): Promise<OwnerListType[]> => {
  let tempList: any[];
  let ownerList: OwnerListType[] = [];
  tempList = personList.value;


  if (tempList) {
    tempList.forEach((item, index) => {
      let key = Object.keys(item)[0];
      let value = item[key] as string;
      ownerList.push({ index: index + 1, id: Number(key), label: value });
    });
  }
  return ownerList;
};
const dialogTitle = ref('')
const detailDisabled = ref(false)
const pageType = ref('')
const personList = ref([])
const ownerList = ref<OwnerListType[]>([]);
onMounted(async () => {
  pageType.value = query.type
  dialogTitle.value = t('action.' + query.type)
  // 获取库存信息
  formData.value = await PlanTaskApi.getPlanTask(query.id)

  // 获得bom需要更新的状态
  refreshStatus.value = await PlanTaskApi.getPlanTaskBomStatus(query.id)
  personList.value  = await TaskDispatchApi.getOwnerList(0,1);
  ownerList.value = await getOwnerListThis();
  queryParams.taskId = query.id
  formData.value.bomDetails = (await PlanTaskBomApi.getPlanTaskBomPage(queryParams)).list

  formData.value.bomDetails.forEach((item) => {
    item.amount = formData.value.projectSubNum * item.amount;
    item.typeName = item.type == 1 ? '是' : '否'
   if(item.owner){
     item.owner = Number(item.owner)
   }
  })

  // 操作日志
  let logParams = {
    pageNo: 1,
    pageSize: 99,
    businessId: formData.value.id,
    businessType: 'PLAN_TASK'
  }
  formData.value.operateLogs = (await getOperateLogPage(logParams)).list

  if ('detail' == query.type || formData.value.status == 2) {
    detailDisabled.value = true
  }
})
const tableRowClassName = ({ row }) => {

switch (row.bomEditStatus) {
  case 1:
    return 'status-1';
  case 2:
    return 'status-2';
  case 3:
    return 'status-3';
  case 4:
    console.log('sss')
    return 'status-4';
  default:
    return '';
}
}
// 责任人
const handleSelectedUser9 = (currentIndex, newValue: any) => {
  formData.value.bomDetails[currentIndex].owner = newValue?.id
}
</script>
<style>
a {
  color: #409eff;
  text-decoration: none;
}

.upload-file-uploader {
  margin-bottom: 10px;
  display: inline-block;
  margin-right: 20px;
}

.hl-card .alter-class {
  position: relative;
  border: solid 1px orange;
  outline: solid 1px orange;
}

.el-form-item__content {
  margin-left: 0px !important;
}
.status-1 {
  background-color: #f2f2f2 !important;
}
.status-2 {
  background-color: #90EE90 !important;

}
.status-3 {
  background-color: #BBFFFF !important;

}
.status-4 {
  background-color: #EE9A00 !important;
}
</style>
