<template>
    <div class="edit-popup">

        <popup ref="popupRef" :title="popupTitle" :async="true" width="80%" @confirm="handleSubmit" @close="handleClose">

            <el-form ref="formRef" :model="formData" label-width="auto" :rules="formRules">

                <el-row :gutter="10">
                    <el-col :span="8">
                        <el-form-item label="作业编码" prop="plan_id" @click="showDialog2 = true">
                            <el-input v-model="zy_code" clearable placeholder="点击选择施工计划" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目名称" prop="plan_id"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-input v-model="project_name" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="项目编码" prop="plan_id"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-input v-model="project_code" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="工序步骤号" prop="plan_id"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-input v-model="process_step_no" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="工序步骤" prop="plan_id"
                            :rules="[{ required: true, message: '不可为空', trigger: 'change' }]">
                            <el-input v-model="process_step" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="图例说明">
                            <div v-if="process_file && process_file.length > 0">
                                <!-- <material-picker v-model="item.uri"/> -->
                                <img v-for="item in process_file" :src="item.uri" style="width:100px" />
                            </div>
                            <div v-else>暂无图例</div>

                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="质量控制点" prop="plan_id"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="quality_control_points" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="计划开始日期" prop="plan_id"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-date-picker class="flex-1 !flex" v-model="plan_start_date" clearable type="date"
                                value-format="YYYY-MM-DD" disabled placeholder="系统自动填写">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="计划结束日期" prop="plan_id"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-date-picker class="flex-1 !flex" v-model="plan_end_date" clearable type="date"
                                value-format="YYYY-MM-DD " disabled placeholder="系统自动填写">
                            </el-date-picker>

                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="班组长" prop="plan_id"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="project_member_name" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="24">
                        <el-form-item label="施工内容" prop="plan_id">
                            <el-input v-model="work_content" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="作业量" prop="plan_id"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="workload" type="number" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="剩余作业量" prop="plan_id"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-input v-model="residue_workload" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="填报人" prop="plan_id">
                            <el-input v-model="filluser" clearable disabled placeholder="系统自动填写" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="填报日期" prop="plan_id"
                            :rules="[{ required: true, message: '不可为空', trigger: 'blur' }]">
                            <el-date-picker class="flex-1 !flex" v-model="filluserdate" clearable type="date"
                                value-format="YYYY-MM-DD " disabled placeholder="系统自动填写">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
                <div class="tit" style="margin:10px 0">
                    人工明细
                </div>
                <el-row>

                    <el-table :data="tableData">
                        <el-table-column label="序号" width="105px">
                            <template #default="{ row }">
                                <el-button @click="handleAdd(row)" size="small">+</el-button>
                                <el-button @click="handleDelete(row)" size="small">-</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column label="姓名" prop="name1">
                            <template #default="{ row, column, $index }">
                                <el-input v-model="row.name1" @click="subjectmu(row, column, $index)" />
                            </template>
                        </el-table-column>
                        <el-table-column label="身份证号" prop="name2">
                            <template #default="{ row }"> <el-input v-model="row.name2" readonly />
                            </template></el-table-column>
                        <el-table-column label="工种" prop="name3">
                            <template #default="{ row }"> <el-input v-model="row.name3" /> </template></el-table-column>

                        <el-table-column label="今日完工量" prop="work_num">
                            <template #default="{ row }">
                                <el-input v-model="row.work_num" type="number" @input="amouttol" />
                            </template>
                        </el-table-column>

                        <el-table-column label="备注" prop="remark">
                            <template #default="{ row }"> <el-input v-model="row.remark" /> </template>
                        </el-table-column>



                        <!-- 其他列 -->
                    </el-table>
                </el-row>

                <div class="tit" style="margin:10px 0">
                    完工量情况
                </div>

                <el-row>
                    <el-col :span="8">
                        <el-form-item label="今日完工量" prop="remark">
                            <el-input v-model="formData.report_workload" type="num" readonly clearable
                                placeholder="请输入今日完工量" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="单位" prop="unit">
                            <el-input v-model="unit" clearable placeholder="请输入单位" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="单价" prop="remark">
                            <el-input v-model="price" clearable placeholder="请输入单价" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="金额" prop="remark">
                            <el-input v-model="formData.report_amount" readonly clearable placeholder="请输入金额" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="现场照片" prop="file">
                            <material-picker v-model="formData.scene_file" :limit="100" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="formData.remark" type="textarea" clearable placeholder="请输入备注" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <div v-if="showDialog">
                    <el-dialog v-model="showDialog" title="选择项目人员" width="70%">
                        <customDialog @customEvent="customEvent" :project_id="project_id"></customDialog>
                    </el-dialog>
                </div>
                <el-dialog v-model="showDialog2" title="选择施工计划" width="70%">
                    <buildplanDialog @customEvent="customEvent2"></buildplanDialog>
                </el-dialog>
                <personnelselector ref="personnel" @confirm="submituser" type="1"></personnelselector>
            </el-form>
        </popup>

    </div>
</template>

<script lang="ts" setup name="projectEdit">
import customDialog from '@/components/project_personnel/index.vue'
import type { FormInstance } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import buildplanDialog from '@/components/build_plan/index.vue'
import { watch } from "vue"
import { buildreportAdd, buildreportEdit, buildreportDetail } from '@/api/build/build_report'

import { toChinesNum } from "@/utils/util";
import { getAllProjectTypes } from '@/api/projecttype'
import { timeFormat } from '@/utils/util'
import { isEmail, isIdCard, isPhone } from '@/utils/validate'
import { deptAll } from '@/api/org/department'
import { getAll } from '@/api/org/organization'
import type { PropType } from 'vue'
import feedback from '@/utils/feedback'
import useUserStore from "@/stores/modules/user";
const userStore = useUserStore();
const userInfo = useUserStore().userInfo
const project_name = ref('')
const project_code = ref('')
const plan_start_date = ref('')
const plan_end_date = ref('')
const project_member_name = ref('')
const workload = ref('')
const work_content = ref('')
const process_step_no = ref('')
const process_step = ref('')
const amount = ref(0)
const unit = ref('')
const today_workload = ref('')
const zy_code = ref('')
const price = ref(0)
const residue_workload = ref('')
const project_id = ref(0)
const quality_control_points = ref('')
const process_file = ref([])
const filluser = userInfo.name
const filluserdate = timeFormat(new Date(), 'YYYY-MM-DD ')
const personnel = ref<any>()
const num = ref(0)
defineProps({
    dictData: {
        type: Object as PropType<Record<string, any[]>>,
        default: () => ({})
    }
})
const emit = defineEmits(['success', 'close'])
const formRef = shallowRef<FormInstance>()
const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('add')
const showDialog = ref(false)
const showDialog2 = ref(false)
const formDataannex = reactive([])
const customEvent2 = (e: any) => {
    formData.plan_id = e.id;
    project_id.value = e.project_id
    zy_code.value = e.zy_code
    project_name.value = e.project_name;
    project_code.value = e.project_code;
    plan_start_date.value = e.plan_start_date
    plan_end_date.value = e.plan_end_date
    project_member_name.value = e.project_member_name
    workload.value = e.workload
    work_content.value = e.work_content
    process_step_no.value = e.process_step_no
    process_step.value = e.process_step
    process_file.value = e.file
    quality_control_points.value = e.quality_control_points
    residue_workload.value = e.residue_workload
    unit.value = e.unit
    price.value = e.price
    if (e.file && e.file.length > 0) {
        process_file.value = e.file
    }

    showDialog2.value = false;

};
const customEvent = (e: any) => {
    tableData.value[num.value].name1 = e.name
    tableData.value[num.value].name2 = e.idcard
    tableData.value[num.value].name3 = e.work_type_text
    tableData.value[num.value].person_id = e.id
    showDialog.value = false;
};
const tableData = ref([
    // 表格数据
    {},
]);


// 计算金额

const getAmount = () => {
    // formData.report_amount
}



watch(tableData.value, () => {
    formData.report_workload = 0
    tableData.value.forEach(item => {
        formData.report_workload += Number(item.work_num) || 0
    });



    formData.report_amount = price.value * formData.report_workload



})


const handleAdd = (row) => {
    // 在 row 后面插入一行数据
    const index = tableData.value.indexOf(row);
    tableData.value.splice(index + 1, 0, {});
};

const handleDelete = (row) => {
    // 删除 row
    const index = tableData.value.indexOf(row);
    tableData.value.splice(index, 1);
};


//计算
const amouttol = (e) => {
    today_workload.value = tableData.value.reduce((total, item) => {
        return total + parseInt(item.work_num);
    }, 0);
}

//监听输入
const amountinput = (e) => {
    // console.log(e)
    if (e && e > 0) {
        formData.amount_daxie = toChinesNum(e)
    }
}
// 弹窗标题
const popupTitle = computed(() => {
    return mode.value == 'edit' ? '编辑施工汇报表' : '新增施工汇报表'
})

// 表单数据
const formData = reactive({
    id: '',
    plan_id: '',
    scene_file: [],
    remark: '',
    report_workload: "",
    report_amount: "",
    person_detail: [],
})


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

})



// 获取详情
const setFormData = async (data: Record<any, any>) => {
    if (data.file && data.file.length > 0) {

        const arry1 = data.file.map((item: any, index: any) => {
            return {
                name: `文件${index + 1}`,
                uri: item
            };
        });
        Object.assign(formDataannex, arry1)

    }


    for (const key in formData) {
        if (data[key] != null && data[key] != undefined) {
            //@ts-ignore
            formData[key] = data[key]
        }
    }
    zy_code.value = data.zy_code
    project_name.value = data.project_name
    project_code.value = data.project_code
    plan_start_date.value = data.plan_start_date
    plan_end_date.value = data.plan_end_date
    project_member_name.value = data.project_member_name
    workload.value = data.workload
    work_content.value = data.work_content
    process_step_no.value = data.process_step_no
    process_step.value = data.process_step
    quality_control_points.value = data.quality_control_points
    residue_workload.value = data.residue_workload

}

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


// 提交按钮
const handleSubmit = async () => {
    formData.file = formDataannex.map((item: any) => item.uri)
    if (tableData.value.length > 0) {
        formData.person_detail = tableData.value.map(({ name1, name2, name3, ...rest }) => rest)
    }
    if (formData.file.length > 0) {
        formData.file = formData.file
    }

    await formRef.value?.validate()

    const data = { ...formData }
    mode.value == 'edit'
        ? await buildreportEdit(data)
        : await buildreportAdd(data)
    popupRef.value?.close()
    emit('success')
}
//项目人员
const subjectmu = (row, i, a) => {
    // console.log(row, i, a)
    if (project_id.value) {
        num.value = a
        showDialog.value = true
    } else {
        feedback.msgError('请先选择施工计划')
    }

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




}

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



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