<template>
  <div class="edit-popup">
    <popup ref="popupRef" :title="popupTitle" :async="true" width="80vw" @confirm="handleSubmit" @close="handleClose">
      <el-form ref="formRef" :model="formData" label-width="90px" :rules="formRules">
        <el-form-item label="单据编号" prop="num">
          <el-input v-model="formData.num" clearable placeholder="系统自动生成" disabled />
        </el-form-item>
        <el-form-item label="项目名称" prop="project_id">
          <el-input v-model="formData.project_name" clearable placeholder="点击选择项目" readonly @click="showDialog = true" />
        </el-form-item>
        <el-form-item label="项目编号" prop="project_num">
          <el-input v-model="formData.project_num" clearable readonly />
        </el-form-item>
        <el-form-item label="项目负责人" prop="head">
          <el-input v-model="formData.head" clearable placeholder="请输入项目负责人" />
        </el-form-item>
        <el-form-item label="登记日期" prop="apptime">
          <el-date-picker class="flex-1 !flex" v-model="formData.apptime" clearable type="date" value-format="YYYY-MM-DD"
            placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="附件">
          <annexUpload :annex="formData.annex" @handleAvatarSuccess="handleAvatarSuccess_four" @delFile="delFileFn" />
        </el-form-item>
        <el-dialog v-model="showDialog" title="选择项目" width="70%">
          <cost_project @customEvent="customEvent"></cost_project>
        </el-dialog>
        <el-dialog v-model="showDialog1" title="选择任务" width="70%">
          <task_type @customEvent="customEvent1"></task_type>
        </el-dialog>

        <div v-if="showDialog3">
          <personnelselector ref="personnel" @confirm="submituser" type="1">
          </personnelselector>
        </div>


        <div style="margin-bottom: 30px;">任务明细</div>
        <div style="margin-bottom: 30px;">
          <el-table :data="formData.task_detail">
            <el-table-column label="序号" v-if="mode == 'add'" width="150px">
              <template #default="{ row }">
                <el-button @click="handleAdd(row)">+</el-button>
                <el-button @click="handleDelete(row)">-</el-button>
              </template>
            </el-table-column>
            <el-table-column label="任务名称" prop="task_name" width="200px">
              <template #default="scope">
                <el-input v-model="scope.row.task_name" readonly @click="showDialog1 = true, tableIndex = scope.$index"
                  placeholder="点击选择" />
              </template>
            </el-table-column>
            <el-table-column label="任务次级" prop="level" width="200px">
              <template #default="{ row }">
                <el-input v-model="row.level" :readonly="mode == 'edit'" />
              </template>
            </el-table-column>
            <el-table-column label="工序" prop="process" width="200px">
              <template #default="{ row }">
                <el-input v-model="row.process" :readonly="mode == 'edit'" />
              </template>
            </el-table-column>
            <el-table-column label="任务类型" prop="task_type_id" width="200px">
              <template #default="{ row }">
                <el-select class="flex-1" v-model="row.task_type_id" clearable placeholder="请选择任务类型">
                  <el-option v-for="(item, index) in dictData.task_type" :key="index" :label="item.name"
                    :value="parseInt(item.value)" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="专业类型" prop="professional_type" width="200px">
              <template #default="{ row }">
                <el-select class="flex-1" v-model="row.professional_type" clearable placeholder="请选择专业类型">
                  <el-option v-for="(item, index) in dictData.major_type" :key="index" :label="item.name"
                    :value="item.value" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="工程师" prop="engineer" width="200px">
              <template #default="scope">
                <el-input v-model="scope.row.engineer" :readonly="mode == 'edit'"
                  @click="userclick(scope.$index, 'engineer')" />
              </template>
            </el-table-column>
            <el-table-column label="一级审核人" prop="first_reviewer" width="200px">
              <template #default="scope">
                <el-input v-model="scope.row.first_reviewer" :readonly="mode == 'edit'"
                  @click="userclick(scope.$index, 'first_reviewer')" />
              </template>
            </el-table-column>
            <el-table-column label="二级审核人" prop="secondary_reviewer" width="200px">
              <template #default="scope">
                <el-input v-model="scope.row.secondary_reviewer" :readonly="mode == 'edit'"
                  @click="userclick(scope.$index, 'secondary_reviewer')" />
              </template>
            </el-table-column>
            <el-table-column label="三级审核人" prop="third_level_reviewer" width="200px">
              <template #default="scope">
                <el-input v-model="scope.row.third_level_reviewer" :readonly="mode == 'edit'"
                  @click="userclick(scope.$index, 'third_level_reviewer')" />
              </template>
            </el-table-column>
            <el-table-column label="天数" prop="days" width="200px">
              <template #default="{ row }">
                <el-input v-model="row.days" :readonly="mode == 'edit'" />
              </template>
            </el-table-column>
            <el-table-column label="开始日期" prop="start_date" width="220px">
              <template #default="{ row }">
                <el-date-picker v-model="row.start_date" clearable type="date" value-format="YYYY-MM-DD"
                  placeholder="请选择日期">
                </el-date-picker>
              </template>
            </el-table-column>
            <el-table-column label="结束日期" prop="end_date" width="220px">
              <template #default="{ row }">
                <el-date-picker v-model="row.end_date" clearable type="date" value-format="YYYY-MM-DD"
                  placeholder="请选择日期">
                </el-date-picker>
              </template>
            </el-table-column>
            <el-table-column label="中标金额(元)" prop="bid_winning_amount" width="200px">
              <template #default="{ row }">
                <el-input v-model="row.bid_winning_amount" :readonly="mode == 'edit'" />
              </template>
            </el-table-column>
            <el-table-column label="送审造价(元)" prop="cost" width="200px">
              <template #default="{ row }">
                <el-input v-model="row.cost" :readonly="mode == 'edit'" />
              </template>
            </el-table-column>
            <el-table-column label="第三方核定金额(元)" prop="approved_amount" width="200px">
              <template #default="{ row }">
                <el-input v-model="row.approved_amount" :readonly="mode == 'edit'" />
              </template>
            </el-table-column>
            <el-table-column label="施工单位" prop="construction_unit" width="200px">
              <template #default="{ row }">
                <el-input v-model="row.construction_unit" :readonly="mode == 'edit'" />
              </template>
            </el-table-column>
            <el-table-column label="联系人" prop="contact" width="200px">
              <template #default="{ row }">
                <el-input v-model="row.contact" :readonly="mode == 'edit'" />
              </template>
            </el-table-column>
            <el-table-column label="联系电话" prop="contact_phone" width="200px">
              <template #default="{ row }">
                <el-input v-model="row.contact_phone" :readonly="mode == 'edit'" />
              </template>
            </el-table-column>
            <el-table-column label="备注" prop="remark" width="200px">
              <template #default="{ row }">
                <el-input v-model="row.remark" :readonly="mode == 'edit'" />
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
    </popup>
  </div>
</template>

<script lang="ts" setup name="taskAllocationEdit">
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { apiTaskAllocationAdd, apiTaskAllocationEdit, apiTaskAllocationDetail } from '@/api/task_allocation'
import type { PropType } from 'vue'
defineProps({
  dictData: {
    type: Object as PropType<Record<string, any[]>>,
    default: () => ({})
  }
})
const a = (e) => {
  console.log(e.$index)
}
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const showDialog = ref(false)
const showDialog1 = ref(false)
const showDialog3 = ref(false)
const personnel = ref<any>()

const handleAvatarSuccess_four = (response: any) => {
  // @ts-ignore
  response.code != 0 ? formData.annex.push({ uri: response.data.uri, name: response.data.name }) : ElMessage.error(response.msg);
};

// 删除上传的文件
const delFileFn = (index: number) => { formData.annex.splice(index, 1) }

// 弹窗标题
const popupTitle = computed(() => {
  return mode.value == 'edit' ? '编辑任务分配' : '新增任务分配'
})

// 表单数据
const formData = reactive({
  id: '',
  dataid: '',
  num: '',
  project: '',
  project_name: "",
  project_num: '',
  head: '',
  apptime: '',
  annex: [],
  task_detail: [{
    task_name: '',
    task_name_id: '',
    process: '',
    task_type_id: '',
    professional_type: '',
    engineer: '',
    engineer_id: '',
    level: '',
    first_reviewer: '',
    first_reviewer_id: '',
    secondary_reviewer: '',
    secondary_reviewer_id: '',
    third_level_reviewer: '',
    third_level_reviewer_id: '',
    bid_winning_amount: '',
    cost: '',
    approved_amount: '',
    construction_unit: '',
    construction_unit_id: '',
    contact: '',
    contact_phone: '',
    days: '',
    start_date: '',
    end_date: '',
    remark: '',
  }]
})

const handleAdd = () => {
  formData.task_detail.push({
    task_name: '',
    task_name_id: '',
    process: '',
    task_type_id: '',
    professional_type: '',
    engineer: '',
    engineer_id: '',
    level: '',
    first_reviewer: '',
    first_reviewer_id: '',
    secondary_reviewer: '',
    secondary_reviewer_id: '',
    third_level_reviewer: '',
    third_level_reviewer_id: '',
    bid_winning_amount: '',
    cost: '',
    approved_amount: '',
    construction_unit: '',
    construction_unit_id: '',
    contact: '',
    contact_phone: '',
    days: '',
    start_date: '',
    end_date: '',
    remark: '',
  })
}


const handleDelete = (row: any) => {
  if (formData.task_detail.length == 1) return
  const index = formData.task_detail.indexOf(row);
  formData.task_detail.splice(index, 1);
}

const tableIndex = ref(0)

const customEvent = (e) => {
  formData.project = e.id
  formData.project_name = e.project_name
  formData.project_num = e.project_num

  showDialog.value = false
}

const customEvent1 = (e) => {
  formData.task_detail[tableIndex.value].task_name = e.name
  formData.task_detail[tableIndex.value].task_name_id = e.id
  formData.task_detail[tableIndex.value].level = e.level
  showDialog1.value = false
}

const tableKey = ref('')
//打开弹窗
const userclick = async (e: any, key) => {
  tableIndex.value = e
  tableKey.value = key
  showDialog3.value = true
  await nextTick()
  personnel.value.open()
  console.log(tableIndex.value, tableKey.value)

}

//确认
const submituser = (e: any) => {
  formData.task_detail[tableIndex.value][tableKey.value] = e.name
  formData.task_detail[tableIndex.value][tableKey.value + '_id'] = e.id
  showDialog3.value = false
}

// 表单验证
const formRules = reactive<any>({

})


// 获取详情
const setFormData = async (data: Record<any, any>) => {
  for (const key in formData) {
    if (data[key] != null && data[key] != undefined) {
      //@ts-ignore
      formData[key] = data[key]
    }
  }


}

const getDetail = async (row: Record<string, any>) => {
  const data = await apiTaskAllocationDetail({
    id: row.id
  })
  setFormData(data)
}


// 提交按钮
const handleSubmit = async () => {

  await formRef.value?.validate()
  const data = { ...formData, }
  mode.value == 'edit'
    ? await apiTaskAllocationEdit(data)
    : await apiTaskAllocationAdd(data)
  popupRef.value?.close()
  emit('success')
}

//打开弹窗
const open = (type = 'add') => {
  mode.value = type
  popupRef.value?.open()
}

// 关闭回调
const handleClose = () => {
  emit('close')
}



defineExpose({
  open,
  setFormData,
  getDetail
})
</script>
