<template>
    <div class="">
        <el-button type="primary" icon="Plus" @click="searchHandle('添加')" style="margin-left: 5px;">添加</el-button>
        <el-dialog v-model="outerVisible" :title="data.drawerTiti" width="1200" style="max-height: 900px;overflow-y: auto;" draggable destroy-on-close>
            <el-form :model="data.initParam"
            ref="ruleFormRef"
            :rules="rules"
            :disabled="data.drawerTiti=='详情'?true:false"
            label-width="160px">
                <el-form-item label="项目名称" prop="T_name">
                    <el-input v-model="data.initParam.T_name" />
                </el-form-item>
                <el-form-item label="项目地址" prop="T_address">
                    <el-input v-model="data.initParam.T_address" />
                </el-form-item>
                <el-form-item label="预计签约时间" prop="T_predict_sign_time">
                    <el-date-picker v-model="data.initParam.T_predict_sign_time" value-format="YYYY-MM-DD" type="date" placeholder="预计签约时间" />
                </el-form-item>
                <el-form-item label="服务内容" prop="ServiceItems">
                    <el-table :data="data.initParam.ServiceItems"  border style="width: 100%">
                        <el-table-column type="index" label="序号" width="60"/>
                        <el-table-column prop="address" label="服务类型" show-overflow-tooltip  width="100">
                            <template #default="scope">
                                {{ scope.row.ServiceItem.ServiceType.T_name }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="address" label="销售类型" show-overflow-tooltip  width="100">
                            <template #default="scope">
                                {{ scope.row.ServiceItem.T_sale_type }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="address" label="服务内容" show-overflow-tooltip >
                            <template #default="scope">
                                {{ scope.row.ServiceItem.T_name }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="address" label="型号" show-overflow-tooltip >
                            <template #default="scope">
                                {{ scope.row.ServiceItem.T_model }}
                            </template>
                        </el-table-column>
                        <el-table-column prop="address" label="规格" show-overflow-tooltip  width="80">
                            <template #default="scope">
                                {{ scope.row.ServiceItem.T_spec }}
                            </template>
                        </el-table-column>
                        <el-table-column label="数量"  width="100">
                            <template #default="scope">
                                <el-input v-model.number="scope.row.T_quantity" style="width:75px" />
                            </template>
                        </el-table-column>
                        <el-table-column label="单价"  width="100">
                            <template #default="scope">
                                <!-- <el-input v-model.number="scope.row.T_unit_price" style="width:75px" /> -->
                                <el-input v-model.number="scope.row.T_unit_price" type="number" style="width:75px"></el-input>
                            </template>
                        </el-table-column>
                        <el-table-column prop="address" label="金额" show-overflow-tooltip >
                            <template #default="scope">
                                {{ scope.row.T_quantity *  scope.row.T_unit_price}}
                            </template>
                        </el-table-column>
                        <el-table-column prop="T_remark" label="备注" show-overflow-tooltip>
                            <template #default="scope">
                                <el-input v-model="scope.row.T_remark" style="width:100%" />
                            </template>
                        </el-table-column>
                        <!-- <el-table-column prop="address" label="操作" width="80" fixed="right">
                            <template #default="scope">
                                <el-button link type="danger" size="small" :icon="Delete" @click="onclickdelete(scope)">删除</el-button>
                            </template>
                        </el-table-column> -->
                    </el-table>
                    <el-button icon="Plus" v-if="data.drawerTiti!='详情'" style="margin-top: 10px;" @click="showinnerVisible">添加</el-button>
                </el-form-item>
                <el-form-item label="总金额">
                    {{ moneyFun() }}
                </el-form-item>
                <el-form-item label="最终优惠金额">
                    <div style="display: flex;align-items: center;">
                        <el-input v-model="data.initParam.T_discount_money" /><span style="padding-left: 10px">元</span>
                    </div>
                </el-form-item>
                <el-form-item label="是否有居间费" prop="T_have_brokerage_fee">
                    <el-radio-group v-model="data.initParam.T_have_brokerage_fee">
                        <el-radio :label="true">是</el-radio>
                        <el-radio :label="false">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="居间费金额" prop="T_brokerage_fee_money">
                    <el-input v-model="data.initParam.T_brokerage_fee_money" />
                </el-form-item>
                <el-form-item label="状态" v-if="data.drawerTiti=='详情'">
                    <el-tag :type="
                                ['1','2'].includes(props.fromData.T_audit)?'info':
                                ['3','5'].includes(props.fromData.T_audit)?'primary':
                                ['4','6'].includes(props.fromData.T_audit)?'danger':''">
                                {{ 
                                    props.fromData.T_audit=='1'?'待提交审核':
                                    props.fromData.T_audit=='2'?'待审核':
                                    props.fromData.T_audit=='3'?'财务通过':
                                    props.fromData.T_audit=='4'?'财务驳回':
                                    props.fromData.T_audit=='5'?'总经理通过':
                                    props.fromData.T_audit=='6'?'总经理驳回':''
                                }}
                            </el-tag>
                </el-form-item>
                <el-form-item label="成本会计审批意见" v-if="data.drawerTiti=='详情'">
                    <el-tag type="info">
                        {{ props.fromData.T_finance_approval_opinion?props.fromData.T_finance_approval_opinion:'暂无' }}
                    </el-tag>
                </el-form-item>
                <el-form-item label="总经理审批意见" v-if="data.drawerTiti=='详情'">
                    <el-tag type="info">
                        {{ props.fromData.T_manager_approval_opinion?props.fromData.T_manager_approval_opinion:'暂无'}}
                    </el-tag>
                </el-form-item>
                <el-form-item v-if="data.drawerTiti!='详情'">
                    <el-button type="primary" @click="onSubmit(ruleFormRef)">立即提交</el-button>
                    <el-button @click="outerVisible = false">取消</el-button>
                </el-form-item>
            </el-form>
            <el-dialog v-model="innerVisible" draggable destroy-on-close title="服务内容"  width="800" append-to-body>
                <div>
                    <el-form :model="data.initParam" :inline="true">
                        <el-form-item label="服务类型" prop="T_service_type_id">
                            <el-select v-model="data.initParamType.T_service_type_id" clearable placeholder="请选择服务类型">
                                <el-option v-for="item in data.options" :key="item.Id" :label="item.T_name" :value="item.Id" />
                            </el-select>
                        </el-form-item>
                        <el-form-item label="销售类型">
                            <el-select v-model="data.initParamType.T_sale_type" clearable placeholder="请选择销售类型">
                                <el-option v-for="item in data.optionsType" :key="item.T_name" :label="item.T_name" :value="item.T_name" />
                            </el-select>
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="onclicksearch">查询</el-button>
                        </el-form-item>
                    </el-form>
                    <el-table :data="data.tableDataType"
                    :row-key="(row:any)=>row.Id"
                     ref="multipleTableRef" 
                     @select="handleChange"
                    style="width: 100%" max-height="500" border>
                        <el-table-column type="selection" label="服务内容" width="55" :reserve-selection="true"/>
                        <el-table-column label="服务类型" width="120">
                            <template #default="scope">{{ scope.row.ServiceType.T_name }}</template>
                        </el-table-column>
                        <el-table-column label="销售类型" width="120">
                            <template #default="scope">{{ scope.row.T_sale_type }}</template>
                        </el-table-column>
                        <el-table-column label="服务内容" width="120" show-overflow-tooltip >
                            <template #default="scope">{{ scope.row.T_name }}</template>
                        </el-table-column>
                        <el-table-column label="型号" prop="T_model" width="120" />
                        <el-table-column label="规格" prop="T_spec" show-overflow-tooltip />
                    </el-table>
                </div>
            </el-dialog>
        </el-dialog>
    </div>
</template>

<script setup lang='ts'>
import { ref, reactive,watch} from 'vue';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'

import { ServiceType_List_Post,ServiceItem_List_Post,
    ContractReview_Add_Post,
    ContractReview_Edit_Post} from '@/api/contractReview/index'
const outerVisible = ref(false)
const innerVisible = ref(false)

const ruleFormRef = ref<FormInstance>()
const props:any = defineProps({
    fromData:{}
})
watch(()=>outerVisible.value,(newData)=>{
    if(newData && data.drawerTiti!='新增'){//打开
        let arr = {...props.fromData}
        console.log('--',arr)
        for (let key in arr) {  
            if (data.initParam.hasOwnProperty(key)) {  
                data.initParam[key] = arr[key];
            }
        }  
        data.initParam.ServiceItems = arr.ServiceItemList
    }
},{deep:true})
const data:any = reactive({
    drawerTiti: '',
    initParam: {
        T_name: '',
        T_address: '',
        T_predict_sign_time: '',
        T_money:0,
        T_have_brokerage_fee: false,
        T_discount_money:0,
        T_brokerage_fee_money:0,
        ServiceItems:[]
    },
    fromData: {},
    options: [],
    optionsType: [{ T_name: '/' }, { T_name: '软件' }, { T_name: '硬件' }],
    initParamType:{
        T_service_type_id:'',
        T_sale_type:'',
        page:1,
        page_z:999999
    },
    tableData:[],
    tableDataType:[]
})
const rules = reactive({
    T_name: [{ required: true, message: '必填项', trigger: 'blur' }],
    T_address: [{ required: true, message: '必填项', trigger: 'blur' }],
    T_predict_sign_time: [{ required: true, message: '必填项', trigger: 'blur' }],
    T_have_brokerage_fee: [{ required: true, message: '必填项', trigger: 'blur' }],
    T_brokerage_fee_money: [{  
        validator: (rule:any, value:any, callback:any) => {  
            if (data.initParam.T_have_brokerage_fee && !value) {  
            return callback(new Error('居间费金额不能为空'));  
            }  
            callback();  
        },  
        trigger: ['blur','change'],  
        }],
    ServiceItems: [{ required: true, message: '必填项', trigger: 'change' }],
})

const multipleTableRef = ref()
const handleChange = async (row:any)=>{
    let arr:any = []
    let repeats = [...new Map(row.map((item:any) => [item.Id, item])).values()]//去重
    let ServiceItems = [...data.initParam.ServiceItems]
    repeats.forEach((item:any) => {
        const flag = ServiceItems.find((obj:any) => item.Id === obj.ServiceItem.Id); 
        if(flag){//已经存在
            arr.push({...flag})
        }else{//不存在
            arr.push({
                ServiceItem:item,
                T_quantity:0,
                T_remark: "",
                T_unit_price:0,
                T_service_item_id:item.Id
            })
        }
    })
    data.initParam.ServiceItems = arr.sort((a:any, b:any) => a.ServiceItem.Id - b.ServiceItem.Id);  
}
const showinnerVisible = async (row:any) => {
    innerVisible.value = true
    await ServiceItemApi()
    await getServiceList()
    //打开时勾选上对应的选项
    if(data.initParam.ServiceItems){
        data.initParam.ServiceItems.map((item:any) => {  
            data.tableDataType.map((row:any) => {
                if(item.ServiceItem.Id === row.Id){
                    multipleTableRef.value!.toggleRowSelection(row)
                }
            })
        }); 
    }
}


const moneyFun = ()=>{
    let total = data.initParam.ServiceItems.reduce((acc:any, item:any) => {  
      return acc + item.T_quantity * item.T_unit_price;  
    }, 0);  
    data.initParam.T_money = total
    return total+'元'; 
}
/**
 * 
 * @param row 删除列
 */
const onclickdelete = async (row:any) => data.initParam.ServiceItems.splice(row.$index,1)



const getServiceList = async () => {
    const result: any = await ServiceType_List_Post({ page: 1, page_z: 9999, })
    if (result.Code == 200) {
        data.options = result.Data.Data || []
    }
}
const searchHandle = (row: any) => {
    data.initParam = {
        T_name: '',
        T_address: '',
        T_predict_sign_time: '',
        T_money:0,
        T_have_brokerage_fee: false,
        T_brokerage_fee_money:null,
        ServiceItems:[]
    }
    outerVisible.value = true
    data.drawerTiti = '新增'
}
const ServiceItemApi = async ()=>{
    const result:any = await ServiceItem_List_Post(data.initParamType)
    if(result.Code==200){
        data.tableDataType = result.Data.Data || []
    }
}
const onSubmit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid:any, fields:any) => {
    if (valid) {
        console.log('submit!',data.initParam)
        if(data.drawerTiti=='新增'){
            ContractReview_AddtApi()
        }else{
            ContractReview_EditApi()
        }
    }
  })
}

const emit = defineEmits<{ (event: 'successFun', value:boolean): void }>()
/**
 * 新增
 */
 const ContractReview_AddtApi = async ()=>{
    let obj = {...data.initParam}
    obj.ServiceItems = JSON.stringify(obj.ServiceItems)
    const result:any = await ContractReview_Add_Post(obj)
    if(result.Code==200){
        ElMessage.success('新增成功')
        emit('successFun',true)
        outerVisible.value = false
    }
}
/**
 * 编辑
 */
const ContractReview_EditApi = async ()=>{
    let obj = {...data.initParam}
    obj.T_id = props.fromData.Id
    obj.ServiceItems = JSON.stringify(obj.ServiceItems)
    const result:any = await ContractReview_Edit_Post(obj)
    if(result.Code==200){
        ElMessage.success('编辑成功')
        emit('successFun',true)
        outerVisible.value = false
    }
}
const onclicksearch = async ()=>{
    ServiceItemApi()
}
defineExpose({
    outerVisible, data
})
</script>

<style lang="scss" scoped>
/* 隐藏全选框 */
::v-deep .el-table__header-wrapper .el-checkbox {
  display: none;
}
</style>