<template>
    <el-card shadow="never" class="list-card">
        <template #header>
            <div class="top_nav flex">
                <div class="nav_list" v-for="(item, index) in customerNav" :key='index' v-show="item.show"
                    @click="changeNav(index, item.value,item.perPrefix)">{{ item.label }}<i :class="navIndex == index ? 'on' : ''"></i>
                </div>
            </div>
            <div class="search" v-show="showSearch">
                <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
                    <el-form-item prop="blurry">
                        <el-input v-model="queryParams.blurry" placeholder="搜索关键字" clearable style="width: 240px"
                            @keyup.enter="handleQuery" />
                    </el-form-item>
                    <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-item prop="sendProduct">
                        <el-input v-model="queryParams.sendProduct" placeholder="请输入寄样产品" clearable style="width: 240px"
                            @keyup.enter="handleQuery" />
                    </el-form-item>
                    <el-form-item prop="sendMemberId">
                        <SelectUser v-model="queryParams.sendMemberId" placeholder="请选择寄样人员"></SelectUser>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </template>

        <Table ref="sendRecordTable" :tableParams="tableParams" :btnRole="leftBtn" @handleAdd="handleAdd"
            @handleEdit="handleUpdate" @selectionChange="handleSelectionChange">
        </Table>
    </el-card>
    <!-- 寄样详情 -->
    <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!='--' ?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-if="pageType == 'edit'" v-model="form.customerName" disabled></el-input>
                    <paginationSelect
                        v-model="form.customerId"
                        @changeSelect="changeCustomer"
                        :selectedName="form.customerName"
                        source="sendRecord"
                        :listFn="listCustomer"
                        :params="customerParams"
                        v-else
                    />
                </el-form-item>
                <el-form-item label="关联业务：" class="business-item" prop="resourceType">
                    <resourceSelect
                        :disabled='pageType=="edit" || !form.customerId'
                        v-model="form.resourceType"
                        v-model:resourceTypeId="form.resourceTypeId"
                        :customerId="form.customerId"
                        :resourceName="form.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-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 { SendRecordVO, SendRecordQuery, SendRecordForm } from '@/api/customer/sendRecord/types';
// import SelectUser from '@/components/SelectOrg/SelectUser.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 {formateNullFieldData, listCustomer} from '@/api/customer';
import { listLiaison } from '@/api/customer/liaison';
import paginationSelect from '@/components/common/paginationSelect.vue';
import resourceSelect from '@/components/common/resourceSelect.vue';

const perPrefix = ref<string>('allSendRecord')
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const router = useRouter();
const sendRecordList = ref<SendRecordVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const leftBtn = ref([])
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const tableParams = reactive<tableTypes<SendRecordQuery, SendRecordVO>>({
    menuId: router.currentRoute.value?.meta?.menuId,
    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: false},
        {
            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',
    queryParams: {
        sendRecordBeginTime: undefined,
        sendRecordEndTime: undefined,
        sendProduct: undefined,
        productDescription: undefined,
        receiveLiaisonId: undefined,
        sendMemberId: undefined,
        queryRangeType:0,
    },
    listFn: listSendRecord,
    delFn: delSendRecord,
    importCode: '',
    exportCode: 'EXPORT_SAMPLE_EXCEL',
    commonQueryOrderBy: 'sendRecordTime'
})

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

// 顶部客户类型切换
const customerNav = [
    {label:'全部寄样',value:'0',perPrefix: 'allsendRecord', show: auth.hasPermi('customer:allSendRecord:list')},
    {label:'我的寄样',value:'10',perPrefix: 'sendRecordMy', show: auth.hasPermi('customer:sendRecordMy:list')},
    {label:'下属的寄样',value:'30',perPrefix: 'sendRecordSubordinate', show: auth.hasPermi('customer:sendRecordSubordinate:list')},
]
const navIndex = ref(0)
const changeNav = (index,val,perPrefixVal) =>{
  navIndex.value = index
  tableParams.queryParams.queryRangeType = val
  perPrefix.value = perPrefixVal
  leftBtn.value = [
    {type: 'add', hasPermi: `customer:${perPrefix.value}:add`},
    {type: 'edit', hasPermi: `customer:${perPrefix.value}:edit`},
    {type: 'remove', hasPermi: `customer:${perPrefix.value}:remove`},
    {type: 'import', hasPermi: `customer:${perPrefix.value}:import`},
    {type: 'export', hasPermi: `customer:${perPrefix.value}:export`}
  ]
  handleQuery()
}
changeNav(0,'0','allSendRecord')

const daterange = ref('')
const getDate = (val: string[] | null) => {
    tableParams.queryParams.sendRecordBeginTime = val ? val[0] : ''
    tableParams.queryParams.sendRecordEndTime = val ? val[1] : ''
}

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

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


const initFormData: SendRecordForm = {
  id: undefined,
  sendRecordTime: undefined,
  sendProduct: undefined,
  productDescription: undefined,
  receiveLiaisonId: undefined,
  sendMemberId: undefined,
  customerId: undefined,
  isDelete: undefined,
  enabled: undefined,
  ownerBy: undefined,
  sort: undefined,
  recordAmount: undefined,
  resourceType: undefined,
  resourceTypeId: undefined,
  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: "blur" }
    ],
  }
});

// 获取客户列表数据
const customerParams = {
    commonScope: 1,
    commonScopeType: '10',
    customerForm: 10,
    hasPublicCustomer: 0,
    hasGarbageCustomer:0,
    customerName: '',
}

const changeCustomer = (data) => {
  getLiaison(data.id)
}

// 获取联系人数据（收样人员）
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|string }) => {
                let obj = { label: item.name, value: item.id as string}
                return obj
            })
        }
    })
}

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

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

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
    daterange.value = undefined
    tableParams.queryParams.sendRecordBeginTime = ''
    tableParams.queryParams.sendRecordEndTime = ''
  handleQuery();
}

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

const pageType= ref()

/** 新增按钮操作 */
const handleAdd = () => {
    reset();
  dialog.visible = true;
  pageType.value='add'
  dialog.title = "添加寄样记录";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: SendRecordVO) => {
  reset();

  const _id = row?.id || ids.value[0]
  const res = await getSendRecord(_id);
  Object.assign(form.value, res.result);
    getLiaison(form.value.customerId)
    // changeBusiness(form.value.resourceType)
    form.value.resourceTypeId = res.result.resourceTypeId
  dialog.visible = true;
  detailDialog.value = false
  pageType.value='edit'
  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 = formateNullFieldData(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{
  :deep(.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>
