<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <!-- <el-form-item label="申购编号" prop="applyPurchaseId">
                <el-input maxlength="100" v-model="queryParams.applyPurchaseId" placeholder="请输入申购编号" clearable
                    @keyup.enter="handleQuery" />
            </el-form-item> -->

            <el-form-item label="申购说明" prop="applyPurchaseExplain">
                <el-input maxlength="100" v-model="queryParams.applyPurchaseExplain" placeholder="请输入申购说明" clearable
                    @keyup.enter="handleQuery" />
            </el-form-item>

            <!-- <el-form-item label="状态" prop="applyPurchaseState">
                <el-select v-model="queryParams.applyPurchaseState" placeholder="请选择状态" clearable @change="handleQuery">
                    <template v-for="dict in com_apply_state" :key="dict.value">
                        <el-option :label="dict.label" :value="dict.value"
                            v-if="['10', '20', '30', '50'].includes(dict.value)" />
                    </template>
                </el-select>
            </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>

        <el-row :gutter="10" class="mb8" style="min-height:32px">
            <!-- <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd"
                    v-hasPermi="['applyPurchase:applyPurchase:add']" >新增
                </el-button>
            </el-col> 
            <el-col :span="1.5">
                <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
                    v-hasPermi="['applyPurchase:applyPurchase:edit']" >修改
                </el-button>
            </el-col>
            <el-col :span="1.5" v-hasPermi="['applyPurchase:applyPurchase:remove']">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete">删除
                </el-button>
            </el-col>-->
            <el-col :span="1.5" v-hasPermi="['applyPurchase:applyPurchase:export']">
                <el-button type="warning" plain icon="Download" @click="handleExport">导出
                </el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-card shadow="never">
            <el-table ref="tableRef" v-loading="loading" :data="applyPurchaseList"
                @selection-change="handleSelectionChange" :default-sort="defaultSort" @sort-change="handleSortChange">
                <!-- <el-table-column type="selection" width="55" align="center"
                v-hasPermi="['applyPurchase:applyPurchase:edit', 'applyPurchase:applyPurchase:remove']" /> -->
                <el-table-column type="expand" width="30">
                    <template #default="scope">
                        <div class="padding">
                            <el-descriptions :column="1">
                                <!-- <el-descriptions-item label="申购编号">
                                {{ scope.row.applyPurchaseId }}
                            </el-descriptions-item> -->
                                <el-descriptions-item label="申购说明">
                                    {{ scope.row.applyPurchaseExplain }}
                                </el-descriptions-item>
                                <el-descriptions-item label="申购状态">
                                    <dict-tag :options="com_apply_state" :value="scope.row.applyPurchaseState"
                                        style="display:inline-block" />
                                </el-descriptions-item>
                                <el-descriptions-item label="创建者">
                                    {{ scope.row.nickName }}
                                </el-descriptions-item>
                                <el-descriptions-item label="创建时间">
                                    {{ parseTime(scope.row.createTime), "{y}-{m}-{d} {h}:{i}:{s}" }}
                                </el-descriptions-item>
                            </el-descriptions>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="序号" align="center" type="index" width="50" />
                <!-- <el-table-column label="申购编号" align="center" prop="applyPurchaseId" width="300px" /> -->
                <el-table-column label="申购说明" align="center" prop="applyPurchaseExplain"
                    :show-overflow-tooltip="true" />
                <el-table-column label="状态" align="center" prop="applyPurchaseState">
                    <template #default="scope">
                        <dict-tag :options="com_apply_state" :value="scope.row.applyPurchaseState" />
                    </template>
                </el-table-column>
                <el-table-column label="创建者" align="center" prop="nickName" />
                <el-table-column label="创建时间" align="center" prop="createTime" width="180" sortable="custom"
                    :sort-orders="['descending', 'ascending']">
                    <template #default="scope">
                        <span>{{ parseTime(scope.row.createTime) }}</span>
                    </template>
                </el-table-column>
                <!--    <el-table-column label="更新者" align="center" prop="updateBy" />
            <el-table-column label="更新时间" align="center" prop="updateTime" width="180">
                <template #default="scope">
                    <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
                </template>
            </el-table-column>
           <el-table-column label="备注" align="center" prop="remark" /> -->
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200"
                    fixed="right" v-hasPermi="['applyPurchase:applyPurchase:query', 'warehouse:warehouse:purchase']">
                    <template #default="scope">
                        <el-button link type="primary" icon="View" @click="handleShowApplyPurchaseDetail(scope.row)"
                            v-hasPermi="['applyPurchase:applyPurchase:query']">详细
                        </el-button>
                        <el-button link icon="SwitchButton" type="info" @click="handleRevoke(scope.row)"
                            v-if="scope.row.isWithdraw == '1'">撤回
                        </el-button>
                        <el-button link icon="Edit" type="success" @click="handleEidt(scope.row)"
                            v-else-if="scope.row.applyPurchaseState == '30' || scope.row.applyPurchaseState == '50'"
                            v-hasPermi="['warehouse:warehouse:purchase']">编辑
                        </el-button>
                        <!-- <el-button link icon="Edit" type="success" @click="handleUpdate(scope.row)"
                        v-hasPermi="['applyPurchase:applyPurchase:edit']" >修改
                    </el-button>
                    <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['applyPurchase:applyPurchase:remove']">删除
                    </el-button> -->
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改物料管理-物料申购对话框 -->
        <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
            <el-form ref="applyPurchaseRef" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="申购说明" prop="applyPurchaseExplain">
                    <el-input maxlength="300" v-model="form.applyPurchaseExplain" type="textarea" placeholder="请输入内容" />
                </el-form-item>
                <el-divider content-position="center">物料管理-物料申购详情信息</el-divider>
                <el-row :gutter="10" class="mb8" style="min-height:32px">
                    <el-col :span="1.5">
                        <el-button type="primary" icon="Plus" @click="handleAddApplyPurchaseDetails">添加</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="danger" icon="Delete" @click="handleDeleteApplyPurchaseDetails">删除</el-button>
                    </el-col>
                </el-row>
                <el-table :data="applyPurchaseDetailsList" :row-class-name="rowApplyPurchaseDetailsIndex"
                    @selection-change="handleApplyPurchaseDetailsSelectionChange" ref="applyPurchaseDetails">
                    <el-table-column type="selection" width="50" align="center" />
                    <el-table-column label="序号" align="center" prop="index" width="50" />
                    <el-table-column label="申购数量" prop="applyPurchaseNum" width="150">
                        <template #default="scope">
                            <el-input-number v-model="scope.row.applyPurchaseNum" :min="1" :step="1" />
                        </template>
                    </el-table-column>
                    <el-table-column label="impa" prop="materialWarehouseImpa" width="150">
                        <template #default="scope">
                            <el-input maxlength="100" v-model="scope.row.materialWarehouseImpa" placeholder="请输入impa" />
                        </template>
                    </el-table-column>
                    <el-table-column label="物料目录编号" prop="materialWarehouseImpaCode" width="150">
                        <template #default="scope">
                            <el-input maxlength="100" v-model="scope.row.materialWarehouseImpaCode"
                                placeholder="请输入物料目录编号" />
                        </template>
                    </el-table-column>
                    <el-table-column label="描述" prop="materialWarehouseImpaDescription" width="150">
                        <template #default="scope">
                            <el-input maxlength="100" v-model="scope.row.materialWarehouseImpaDescription"
                                placeholder="请输入描述" />
                        </template>
                    </el-table-column>
                    <el-table-column label="单位" prop="materialWarehouseImpaUnit" width="150">
                        <template #default="scope">
                            <el-input maxlength="100" v-model="scope.row.materialWarehouseImpaUnit"
                                placeholder="请输入单位" />
                        </template>
                    </el-table-column>
                    <el-table-column label="规格" prop="materialWarehouseImpaSpecifications" width="150">
                        <template #default="scope">
                            <el-input maxlength="100" v-model="scope.row.materialWarehouseImpaSpecifications"
                                placeholder="请输入规格" />
                        </template>
                    </el-table-column>
                    <el-table-column label="备注" prop="remark" width="150">
                        <template #default="scope">
                            <el-input maxlength="300" v-model="scope.row.remark" type="textarea" placeholder="请输入备注" />
                        </template>
                    </el-table-column>
                </el-table>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>


        <ApplyPurchaseDetail :applyPurchaseId="applyPurchaseId" ref="applyPurchaseDetailSubmitRef" @update="getList" />
    </div>





</template>

<script setup name="ApplyPurchase">
import ApplyPurchaseDetail from "@/components/ApplyPurchase/detail/drawer";
import { clearApplyPurchaseDetails, updateApplyPurchaseDetails as _updateApplyPurchaseDetails } from "@/utils/applyPurchaseDetails";

import { listApplyPurchase, getApplyPurchase, delApplyPurchase, addApplyPurchaseDetails, updateApplyPurchaseDetails, downloadApplyPurchase } from "@/api/applyPurchase/applyPurchase";
import {
    withdrawApply,
} from "@/api/workbench/apply";
import { onMounted } from "vue-demi";
const { proxy } = getCurrentInstance();
const { com_apply_state } = proxy.useDict('com_apply_state');

const router = useRouter();

const applyPurchaseList = ref([]);
const applyPurchaseDetailsList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const applyPurchaseId = ref(null)
const checkedApplyPurchaseDetails = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const defaultSort = ref({ prop: "createTime", order: "descending" });

const data = reactive({
    form: {},
    queryParams: {
        pageNum: 1,
        pageSize: 10,
        applyPurchaseExplain: null,
    },
    rules: {
    }
})
    ;

const { queryParams, form, rules } = toRefs(data);
const baseUrl = import.meta.env.VITE_APP_BASE_API;

/** 查询物料管理-物料申购列表 */
function getList() {
    loading.value = true;
    listApplyPurchase(queryParams.value).then(response => {
        applyPurchaseList.value = response.rows;
        total.value = response.total;
        loading.value = false;
    });
}

function addList() {
    loading.value = true;
    listApplyPurchase(queryParams.value)
        .then(response => {
            applyPurchaseList.value.push(...response.rows);
            total.value = response.total;
            if (applyPurchaseList.value.length >= total.value) finished.value = true;
            loading.value = false;
        })
        .catch(response => {
            loading.value = false;
        });
}

// 下拉刷新
function handlePullDownRefresh() {
    queryParams.value.pageNum = 1;
    applyPurchaseList.value = [];
    addList();
}

// 滚动到底部的事件
function handleReachBottom() {
    queryParams.value.pageNum++;
    addList();
}

// 取消按钮
function cancel() {
    open.value = false;
    reset();
}

// 表单重置
function reset() {
    form.value = {
        applyPurchaseId: null,
        applyPurchaseExplain: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
    }
        ;
    applyPurchaseDetailsList.value = [];
    proxy.resetForm("applyPurchaseRef");
}

/** 搜索按钮操作 */
function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
}

/** 重置按钮操作 */
function resetQuery() {
    proxy.resetForm("queryRef");
    queryParams.value.pageNum = 1;
    proxy.$refs["tableRef"].sort(defaultSort.value.prop, defaultSort.value.order);
    // handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
    ids.value = selection.map(item => item.applyPurchaseId);
    single.value = selection.length != 1;
    multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
    reset();
    open.value = true;
    title.value = "添加物料管理-物料申购";
}

/** 修改按钮操作 */
function handleUpdate(row) {
    reset();
    const applyPurchaseId =
        row.applyPurchaseId || ids.value
    getApplyPurchase(applyPurchaseId).then(response => {
        form.value = response.data;
        applyPurchaseDetailsList.value = response.data.applyPurchaseDetailsList;
        open.value = true;
        title.value = "修改物料管理-物料申购";
    });
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["applyPurchaseRef"].validate(valid => {
        if (valid) {
            form.value.applyPurchaseDetailsList = applyPurchaseDetailsList.value;
            if (form.value.applyPurchaseId != null) {
                updateApplyPurchaseDetails(form.value).then(response => {
                    proxy.$modal.msgSuccess("修改成功");
                    open.value = false;
                    getList();
                });
            } else {
                addApplyPurchaseDetails(form.value).then(response => {
                    proxy.$modal.msgSuccess("新增成功");
                    open.value = false;
                    getList();
                });
            }
        }
    });
}

/** 删除按钮操作 */
function handleDelete(row) {
    const applyPurchaseIds = row.applyPurchaseId || ids.value;
    proxy.$modal.confirm('是否确认删除物料管理-物料申购编号为"' + applyPurchaseIds + '"的数据项？').then(function () {
        return delApplyPurchase(applyPurchaseIds);
    }).then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
    }).catch(() => { });
}

/** 物料管理-物料申购详情序号 */
function rowApplyPurchaseDetailsIndex({ row, rowIndex }) {
    row.index = rowIndex + 1;
}

/** 物料管理-物料申购详情添加按钮操作 */
function handleAddApplyPurchaseDetails() {
    let obj = {};
    obj.applyPurchaseNum = "";
    obj.materialWarehouseImpa = "";
    obj.materialWarehouseImpaCode = "";
    obj.materialWarehouseImpaDescription = "";
    obj.materialWarehouseImpaUnit = "";
    obj.materialWarehouseImpaSpecifications = "";
    obj.remark = "";
    applyPurchaseDetailsList.value.push(obj);
}

/** 物料管理-物料申购详情删除按钮操作 */
function handleDeleteApplyPurchaseDetails() {
    if (checkedApplyPurchaseDetails.value.length == 0) {
        proxy.$modal.msgError("请先选择要删除的物料管理-物料申购详情数据");
    } else {
        const applyPurchaseDetailss = applyPurchaseDetailsList.value;
        const checkedApplyPurchaseDetailss = checkedApplyPurchaseDetails.value;
        applyPurchaseDetailsList.value = applyPurchaseDetailss.filter(function (item) {
            return checkedApplyPurchaseDetailss.indexOf(item.index) == -1
        });
    }
}

/** 复选框选中数据 */
function handleApplyPurchaseDetailsSelectionChange(selection) {
    checkedApplyPurchaseDetails.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
    downloadApplyPurchase(queryParams.value)
    // proxy.download('applyPurchase/applyPurchase/export', {
    //   ...queryParams.value
    // }, `applyPurchase_${new Date().getTime()}.xlsx`)
}

/** 详细按钮操作 */
function handleView(row) {
}

function handleShowApplyPurchaseDetail(row) {
    //// console.log(row.applyPurchaseId)
    applyPurchaseId.value = row.applyPurchaseId
    proxy.$refs["applyPurchaseDetailSubmitRef"].show();
}

function handleRevoke(row) {
    proxy.$modal
        .confirm("是否撤回？")
        .then(() => {
            withdrawApply(row.applyPurchaseId).then(() => {
                proxy.$modal.msg("已撤回");
                getList();
            })
        })
        .catch(() => { });
}

function handleEidt(row) {
    getApplyPurchase(row.applyPurchaseId).then(response => {
        clearApplyPurchaseDetails(false);
        response.data.applyPurchaseDetailsList.map(item => _updateApplyPurchaseDetails(item, false))
        router.push("/warehouse/warehouse?showApplyPurchaseDrawerSubmit=true");
    });
}

/** 排序触发事件 */
function handleSortChange(column, prop, order) {
    queryParams.value.orderByColumn = column.prop;
    queryParams.value.isAsc = column.order;
    getList();
}

onActivated(() => {
    getList();

})

onMounted(() => {
    getList();
})
</script>

