<template>
    <div class="nav_detail">
        <Table ref="sendRecordTable" :tableParams="tableParams" :btnRole="btnRole" :right-btn="[]"
            @handleAdd="handleAdd" @handleEdit="handleUpdate" @selectionChange="handleSelectionChange">
            <template #left-search>
                <el-form :model="queryParams" ref="queryFormRef" :inline="true" class="nav_detail_search">
                    <el-form-item prop="sendRecordTime">
                        <el-date-picker clearable v-model="daterange" type="datetimerange"
                            value-format="YYYY-MM-DD HH:mm:ss" range-separator="-" start-placeholder="寄样时间"
                            end-placeholder="寄样时间" @change="getDate" />
                    </el-form-item>
                </el-form>
            </template>
        </Table>
    </div>
    <!-- 寄样详情 -->
    <el-dialog v-model="detailDialog" center width="680" class="list-dialog" title="寄样详情">
        <div class="form_area flex">
            <div class="form_item">
                <div class="flex">
                    <div class="label">客户名称</div>
                    <div class="value">{{ sendDetailData.customerName }}</div>
                </div>
                <div class="flex">
                    <div class="label">关联业务</div>
                    <div class="value">{{ sendDetailData.resourceName }}</div>
                </div>
                <div class="flex">
                    <div class="label">寄样人员</div>
                    <div class="value">{{ sendDetailData.sendMemberName }}</div>
                </div>
                <div class="flex">
                    <div class="label">收样人员</div>
                    <div class="value">{{ sendDetailData.receiveLiaisonName }}</div>
                </div>
                <div class="flex">
                    <div class="label">寄样日期</div>
                    <div class="value">{{ sendDetailData.sendRecordTime }}</div>
                </div>
                <div class="flex">
                    <div class="label">样品金额</div>
                    <div class="value">{{ sendDetailData.recordAmount?sendDetailData.recordAmount.toFixed(2):'' }}</div>
                </div>
                <div class="flex">
                    <div class="label">寄样产品</div>
                    <div class="value">{{ sendDetailData.sendProduct }}</div>
                </div>
                <div class="flex">
                    <div class="label">创建人员</div>
                    <div class="value">{{ sendDetailData.createByName }}</div>
                </div>
                <div class="flex">
                    <div class="label">创建时间</div>
                    <div class="value">{{ sendDetailData.createTime }}</div>
                </div>
                <div class="flex">
                    <div class="label">样品描述</div>
                    <div class="value">{{ sendDetailData.productDescription }}</div>
                </div>
            </div>
        </div>
        <div style='padding-top:15px;text-align: right'>
            <el-button type="primary" @click="handleUpdate(sendDetailData)">编辑寄样</el-button>
            <el-button @click="sendDel(sendDetailData.id)">删除寄样</el-button>
        </div>
    </el-dialog>
    <!-- 添加或修改寄样记录对话框 -->
    <el-dialog v-model="dialog.visible" center width="680" class="list-dialog" :title="dialog.title" destroy-on-close>
        <div style='padding-top:15px;text-align: right'>
            <!-- <editor v-model="value" style="height: 600px" /> -->
            <el-form ref="sendRecordFormRef" :model="form" :rules="rules" label-width="auto" class="demo-ruleForm"
                status-icon>
                <el-form-item label="客户名称：" prop="customerId">
                    <el-input v-model="props.customerName" disabled></el-input>
                </el-form-item>
                <el-form-item label="关联业务：" class="business-item" prop="resourceType">
                    <resourceSelect
                        disabled
                        v-model="form.resourceType"
                        v-model:resourceTypeId="form.resourceTypeId"
                        :resourceName="props.resourceName"
                    />
                </el-form-item>
                <el-form-item label="寄样人员：" prop="sendMemberId">
                    <SelectUser v-model="form.sendMemberId" placeholder=""></SelectUser>
                </el-form-item>
                <el-form-item label="收样人员：" prop="receiveLiaisonId">
                    <el-select-v2 v-loading="changeCustLoading" v-model="form.receiveLiaisonId" :options="liaisonOption"
                        placeholder="请选择收样人员" filterable />
                </el-form-item>
                <el-form-item label="寄样日期：" prop="sendRecordTime">
                    <el-date-picker clearable v-model="form.sendRecordTime" type="datetime"
                        value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择寄样时间" style="width: 100%;">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="寄样金额：" prop="recordAmount">
                    <el-input type='number' v-model="form.recordAmount" placeholder="请输入寄样金额" >
                        <template #append>元</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="寄样产品：" prop="sendProduct">
                    <el-input v-model="form.sendProduct" type="textarea" placeholder="请输入内容" />
                </el-form-item>
                <el-form-item label="" prop="">
                    <el-input v-model="form.productDescription" maxlength="300" style="width: 100%"
                        placeholder="请输入样品描述" show-word-limit type="textarea" />
                </el-form-item>
            </el-form>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button :loading="buttonLoading" type="primary" @click="submitForm">提交</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup name="SendRecord" lang="ts">
import { listSendRecord, getSendRecord, delSendRecord, addSendRecord } from '@/api/customer/sendRecord';
import { ElButton, ElMessage, ElMessageBox } from 'element-plus';
import { SendRecordVO, SendRecordQuery, SendRecordForm } from '@/api/customer/sendRecord/types';
// import SelectUser from '@/components/SelectOrg/SelectUser.vue';
import CorrelationSelect from '@/components/common/correlationSelect.vue';
import { listDetialByCodes } from "@/api/system/dict/";
import auth from '@/plugins/auth'
import Table from '@/components/Table/index.vue'
import { tableTypes } from '@/components/Table/types'
import request from '@/utils/request';
import { listCustomer } from '@/api/customer';
import { listLiaison } from '@/api/customer/liaison';
import resourceSelect from '@/components/common/resourceSelect.vue';
const props = defineProps({
    resourceType: {
        type: String
    },
    resourceTypeId: {
        type: String
    },
    perPrefix: {
        type: String
    },
    customerId: {
        type: [String, Number]
    },
    customerName: {
        type: String
    },
    resourceName: {
        type: String
    }
})

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();
const sendRecordList = ref<SendRecordVO[]>([]);
const buttonLoading = ref(false);
const changeCustLoading = ref(false);
const loadCustListLoading = ref(false)
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const btnRole = ref([
    { type: 'add', hasPermi: `${props.perPrefix}:detail:tab_jyjl_tj` },
    { type: 'edit', hasPermi: `${props.perPrefix}:detail:tab_jyjl_dr` },
    { type: 'remove', hasPermi: `${props.perPrefix}:detail:tab_jyjl_sc` },
    // { type: 'import', hasPermi: `${props.perPrefix}:detail:tab_jyjl_dr` },
    { type: 'export', hasPermi: `${props.perPrefix}:detail:tab_jyjl_dc` }
])
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const sendRecordFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
    visible: false,
    title: ''
});


const tableParams = reactive<tableTypes<SendRecordQuery, SendRecordVO>>({
    tableColumn: [
        { show: true, label: '寄样日期', prop: 'sendRecordTime', sortable: true },
        {show: true, label: '客户名称', prop: 'customerName', sortable: false},
        { show: true, label: '寄样产品', prop: 'sendProduct', sortable: true },
        {
            show: true,
            label: '样品描述',
            prop: 'productDescription',
            sortable: true,
            render: ({column}: { column: SendRecordVO }) => {
                return [
                    h('div', {class:'vertical'}, column.productDescription),
                ]
            }
        },
        { show: true, label: '样品金额', prop: 'recordAmount', sortable: true, toFixed: true },
        { show: true, label: '收样人员', prop: 'receiveLiaisonName', sortable: false },
        { show: true, label: '寄样人员', prop: 'sendMemberName', sortable: false },
        { show: true, label: '创建时间', prop: 'createTime', sortable: true },
        {
            show: true, label: '操作', width: 200, prop: 'operation', disabledMove: true, render: ({ column }: { column: SendRecordVO }) => {
                return [
                    auth.hasPermi('system:user:demo') ? h(ElButton, { link: true, type: 'primary', onClick: () => { } }, 'demo') : '',
                    h(ElButton, { link: true, type: 'primary', onClick: () => { openDetailDialog(column.id) } }, () => '详情'),
                ]
            }
        },
    ],
    keyId: 'id',
    menuId: router.currentRoute.value?.meta?.menuId,
    queryParams: {
        queryRangeType: 0,
        resourceType:props.resourceType=='10'?'':props.resourceType,
        resourceTypeId:props.resourceType=='10'?'':props.resourceTypeId,
        customerId:props.resourceType=='10'?props.resourceTypeId:'',
        sendRecordBeginTime: '',
        sendRecordEndTime: ''
    },
    listFn: listSendRecord,
    delFn: delSendRecord,
    importCode: '',
    exportCode: 'EXPORT_SAMPLE_EXCEL',
    commonQueryOrderBy: 'sendRecordTime'
})


const initFormData: SendRecordForm = {
    id: undefined,
    sendRecordTime: undefined,
    sendProduct: undefined,
    productDescription: undefined,
    receiveLiaisonId: undefined,
    sendMemberId: undefined,
    customerId: props.customerId,
    isDelete: undefined,
    enabled: undefined,
    ownerBy: undefined,
    sort: undefined,
    recordAmount: undefined,
    resourceType: props.resourceType,
    resourceTypeId: props.resourceTypeId,
    queryRangeType: 0,
}
const data = reactive<PageData<SendRecordForm, SendRecordQuery>>({
    form: { ...initFormData },
    rules: {
        customerId: [
            { required: true, message: "请选择客户", trigger: "change" }
        ],
        sendMemberId: [
            { required: true, message: "请选择寄样人员", trigger: "change" }
        ],
        receiveLiaisonId: [
            { required: true, message: "请选择收样人员", trigger: "change" }
        ],
        sendRecordTime: [
            { required: true, message: "请选择寄样日期", trigger: "change" }
        ],
        sendProduct: [
            { required: true, message: "请选择寄样产品", trigger: "change" }
        ],
    }
});
const daterange = ref('')
const getDate = (val: string[] | null) => {
    tableParams.queryParams.sendRecordBeginTime = val ? val[0] : ''
    tableParams.queryParams.sendRecordEndTime = val ? val[1] : ''
    handleQuery();
}

const { form, rules } = toRefs(data);

const { queryParams } = toRefs(tableParams);

const changeCustomer = (data) => {
    changeCustLoading.value = true
    form.value.receiveLiaisonId = ''
    getLiaison(data)
}

// 获取联系人数据（收样人员）
const liaisonOption = ref([])
const getLiaison = (customerId: string | number) => {
    listLiaison({ pageIndex: 1, pageSize: 999999, customerId, commonScope: 1, commonScopeType: '20' }).then(res => {
        if (res.success) {
            liaisonOption.value = res.result.records.map((item: { name: string, id: number }) => {
                let obj = { label: item.name, value: item.id }
                return obj
            })

        }
        changeCustLoading.value = false
    })
}
/** 取消按钮 */
const cancel = () => {
    reset();
    dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
    form.value = { ...initFormData };
    sendRecordFormRef.value?.resetFields();
}

const sendRecordTable = ref()
/** 搜索按钮操作 */
const handleQuery = () => {
    sendRecordTable.value.getData()
}

/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: SendRecordVO[]) => {
    ids.value = selection.map(item => item.id);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
    reset();
    if (props.customerId) {
        getLiaison(props.customerId)
    }
    dialog.visible = true;
    dialog.title = "添加寄样记录";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: SendRecordVO) => {
    reset();
    let customerId = props.customerId ? props.customerId : row?.customerId
    getLiaison(customerId) // 获取联系人列表
    const _id = row?.id || ids.value[0]
    const res = await getSendRecord(_id);
    Object.assign(form.value, res.result);
    dialog.visible = true;
    detailDialog.value = false
    dialog.title = "修改寄样记录";

}
/** 提交按钮 */
const submitForm = () => {
  sendRecordFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      await addSendRecord(form.value).finally(() =>  buttonLoading.value = false);
      ElMessage.success('提交成功')
      dialog.visible = false;
      await handleQuery();
    }
  });
}


const detailDialog = ref<boolean>(false)
const sendDetailData = ref<SendRecordVO>()

const openDetailDialog = async(id)=>{
  const res = await getSendRecord(id);
  sendDetailData.value = res.result
  detailDialog.value = true
}

const sendDel=(id)=>{
  ElMessageBox.confirm(
      '是否确认删除当前寄样记录？',
      '确认提示',
      { type: 'warning', confirmButtonText: '提交' }
  ).then(() => {
    delSendRecord(id).then(res => {
          if (res.success) {
              ElMessage.success('删除成功')
              detailDialog.value=false
              handleQuery()
          }else{
              ElMessage.error('删除失败')
          }
      })
  }).catch(() => {})
}

onMounted(() => {

});
</script>
<style lang="scss" scoped>
.el-form-item__content{
  :deep(.sle-user-el-input){
    height: 100% !important;
  }
}

.business-item{
    :deep(.el-form-item__content){
        display: flex;
        column-gap: 8px;
        .el-select{
            flex: 1
        }
    }
}
</style>
