<template>
    <div class="app-container">
        <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="100px"
        >
            <el-form-item label="创建时间">
                <el-date-picker
                v-model="queryParams.startTime"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="开始日期"
                @change="() => queryParams.endTime = ''"
                style="width: 130px"
                />
            </el-form-item>
            <el-form-item>-</el-form-item>
            <el-form-item>
                <el-date-picker
                v-model="queryParams.endTime"
                value-format="yyyy-MM-dd"
                type="date"
                placeholder="结束日期"
                :picker-options="{ disabledDate: (t) => t.getTime() < new Date(queryParams.startTime).getTime() - 86400000}"
                style="width: 130px"
                />
            </el-form-item>
            <el-form-item prop="jijuType">
                <el-select
                    v-model="queryParams.jijuType"
                    placeholder="请选择状态"
                    clearable
                    filterable
                    style="width: 240px"
                >
                    <!-- v-for 和 v-if 尽量不要同时使用 -->
                    <el-option
                        v-for="dict in jijuTypes"
                        :key="dict.value"
                        :label="dict.label"
                        :value="dict.value"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item prop="keyWord">
                <el-input
                    v-model="queryParams.keyWord"
                    placeholder="请输入关键字"
                    clearable
                    maxlength="50"
                    style="width: 240px"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item prop="keyWord">
                <el-input
                    v-model="queryParams.deptName"
                    placeholder="请输入分公司名称"
                    clearable
                    maxlength="50"
                    style="width: 240px"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item prop="keyWord">
                <el-input
                    v-model="queryParams.proName"
                    placeholder="请输入工程名称"
                    clearable
                    maxlength="50"
                    style="width: 240px"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item prop="typeName">
                <el-input
                    v-model="queryParams.typeName"
                    placeholder="请输入物资名称"
                    clearable
                    maxlength="50"
                    style="width: 240px"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item prop="modelType">
                <el-input
                    v-model="queryParams.modelType"
                    placeholder="请输入规格型号"
                    clearable
                    maxlength="50"
                    style="width: 240px"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item prop="leasePerson">
                <el-input
                    v-model="queryParams.leasePerson"
                    placeholder="请输入领料人员"
                    clearable
                    maxlength="50"
                    style="width: 240px"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
<!--
            <el-form-item prop="leaseUnitId">
                <treeselect
                    v-model="queryParams.leaseUnitId"
                    :options="unitList" :normalizer="normalizer"
                    :show-count="true" style="width: 240px" :disable-branch-nodes="true"
                    noChildrenText="没有数据了" noOptionsText="没有数据" noResultsText="没有搜索结果"
                    placeholder="请选择往来单位" @select="unitChange"
                />
            </el-form-item>
            <el-form-item prop="leaseProjectId">
                <treeselect
                    v-model="queryParams.leaseProjectId"
                    :options="proList" :normalizer="normalizer"
                    :show-count="true" style="width: 240px" :disable-branch-nodes="true"
                    noChildrenText="没有数据了" noOptionsText="没有数据" noResultsText="没有搜索结果"
                    placeholder="请选择工程名称" @select="proChange"
                />
            </el-form-item>
             <el-form-item prop="impUnitName">
                <el-select v-model="queryParams.impUnitName" placeholder="请选择分公司" clearable style="width: 240px">
                    <el-option
                        v-for="item in impUnitNameList"
                        :key="item.impUnitName"
                        :label="item.impUnitName"
                        :value="item.impUnitName"
                    ></el-option>
                </el-select>
             </el-form-item> -->

            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
            </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="typeList" border :max-height="650">
            <el-table-column align="center" label="序号" type="index">
                <template slot-scope="scope">
                    <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" width="100" label="协议号" prop="agreementCode" />
            <el-table-column  label="分公司"  align="center" prop="deptName"  width="150px" :show-overflow-tooltip="true"/>
            <el-table-column label="单位名称" align="center" prop="unitName" width="180px" />
            <el-table-column label="工程名称" align="center" prop="proName" width="180px" />
            <el-table-column label="物资名称" align="center" prop="typeName" width="140px" />
            <el-table-column label="规格型号" align="center" prop="modelType" width="140px"></el-table-column>
            <el-table-column label="出库数量" align="center" prop="outNum" width="140px"></el-table-column>
            <el-table-column label="物资编码" align="center" prop="maCode"></el-table-column>
            <el-table-column label="出库日期" align="center" prop="outTime" />
            <el-table-column label="机具类型" align="center" prop="jijuType" />
            <el-table-column label="领料单号" align="center" prop="code" />
            <el-table-column label="领料人"   align="center" prop="leasePerson" :show-overflow-tooltip="true" />

        </el-table>

        <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />
    </div>
</template>

<script>
import { getListLeaseQuery, getApplyInfo, getCheckInfo } from '@/api/lease/apply'
import { outInfoList, getDetailsByTypeId, submitOut, submitNumOut, rejectLeaseOut, getOutNumApi,deleteLeaseOut,updatePreNum } from '@/api/lease/out'
import {
    getProjectList,
    getUnitList,
    getImpUnitNameListApi
} from '@/api/back/index.js'
import vueEasyPrint from 'vue-easy-print'
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
// import chapter from '../../../../utils/chapter';
import printJS from 'print-js'
export default {
    name: 'OutBound',
    dicts: ['lease_task_status'],
    components: { vueEasyPrint, Treeselect },
    data() {
        return {
            // 遮罩层
            userId: sessionStorage.getItem('userId'),
            keyId: null,
            loading: true,
            loadingTwo: false,
            loadingView: false, // 查看弹窗的加载状态
            //查看的显示
            showOutView: false,
            //出库的显示
            showOutInfo: false,
            //编码出库的显示
            openCode: false,
            open: false,
            // 选中数组
            ids: [],
            jijuTypes:[{value:"1",label:"机具"},{value:"2",label:"安全工器具"}],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            ViewTotal: 0,
            outTotal: 0,
            dialogTotal: 0,
            // 弹出层标题
            title: '',
            typeList: [],
            //出库数量
            getListOutInfo: [],
            outCodeList: [],
            outNumList: [], //数量弹窗表格数据
            maCodeList: [],
            // 日期范围
            dateRange: [],
            statusDataRange: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                time: null, //申请时间
                taskStatus: '',
                keyWord: '',
                leaseUnitId: null,
                leaseProjectId: null,
                impUnitName: null,
                startTime: null,
                endTime: null,
            },
            unitList: [],
            proList: [],
            impUnitNameList: [],
            //出库的搜索栏
            queryOutInfo: {
                pageNum: 1,
                pageSize: 10
            },
            //查看的搜索栏
            queryOutView: {
                pageNum: 1,
                pageSize: 10,
                keyWord: ''
            },
            outQuery: {
                pageNum: 1,
                pageSize: 10,
                maCode: ''
            },
            form: {
                remark: ''
            },
            // 表单校验
            rules: {},
            openPrint: false,
            printData: {},
            printTableData: [],
            checkDataInfo: {},
            outNum: 0,
            outObj: {},
            parentIdTemp: undefined,
            //领料单
            leaseApplyDetails: [],
            // 领料任务详情数据
            leaseApplyData: {},

            openNum: false, //数量弹窗开关
            numOutForm: {
                //数量表单-车牌号
                carCode: '',
                remark: ''
            },
            titleView: '',
            showView: false,
            getListViewInfo: [],
            idTemp: '',
            publishTask: '',
            kgSignList: [],
            outSignList: [],
            approveSignList: [],
            currentRowData: null, // 当前查看的行数据
            leaseLoading: false,
            taskType: '',
            currentRow: {},
            oldTypeId: '',
            allNum: null,
            ropeNum: null,
            inCountNum: null,
            fileTypeNum: null,
        }
    },
    created() {
        if (this.$route.query.code) {
            this.queryParams.keyWord = this.$route.query.code
        }
        const end = new Date()
        let start = new Date()
        start.setMonth(start.getMonth() - 1)
        this.queryParams.time = [this.format(end), this.format(end)]
        this.queryParams.startTime = this.format(end)
        this.queryParams.endTime = this.format(end)
        this.GetUnitData()
        this.GetProData()
        // this.getImpUnitNameList()
    },
    methods: {
        /** 转换菜单数据结构 */
        normalizer(node) {
            if (node.children && !node.children.length) {
                delete node.children;
            }
            return {
                id: node.id,
                label: node.name,
                children: node.children,
            };
        },
        // 获取 来往单位 列表数据
        async GetUnitData() {
            const res = await getUnitList({})
            this.unitList = res.data
            console.log('🚀 ~ this.unitList:', this.unitList)
        },
        unitChange(val){
            setTimeout(()=>{
                // this.GetProData()
            },500)
        },
        // 获取 工程名称 列表数据
        async GetProData() {
            const params = { unitId: this.queryParams.leaseUnitId}
            const res = await getProjectList({})
            this.proList = res.data
            this.queryParams.leaseProjectId=null
        },
        proChange(val){
            setTimeout(()=>{
                // this.GetUnitData()
            },500)
        },
        // 分公司下拉
        async getImpUnitNameList () {
            try {
                const res = await getImpUnitNameListApi()
                this.impUnitNameList = res.data
            } catch (error) {
                console.log('🚀 ~ error:', error)
            }
        },
        selectable(row, index) {
            if (row.jiJuType == 2 && row.isCheck == '1') {
                return !this.isWithinOneMonth(row.nextCheckTime)
            } else {
                return true
            }
        },
        isWithinOneMonth(dateStr) {
            if (!dateStr) return false

            const inputDate = new Date(dateStr)
            const today = new Date()
            today.setHours(0, 0, 0, 0) // 清除时分秒

            const diffTime = inputDate.getTime() - today.getTime()
            const diffDays = diffTime / (1000 * 60 * 60 * 24)

            return diffDays <= 90
        },
        // 字典数据加载完成后的回调
        onDictReady(dict) {
            // 获取过滤后的状态选项（排除值为1和2的选项）
            const validOptions = dict.type.lease_task_status.filter(item => item.value != 1 && item.value != 2)

            // 如果有有效选项，设置第一个为默认值
            // if (validOptions.length > 0) {
            //     this.queryParams.taskStatus = validOptions[0].value
            // }

            // 执行查询
            this.getList()
        },
        format(date) {
            const y = date.getFullYear()
            const m = String(date.getMonth() + 1).padStart(2, '0')
            const day = String(date.getDate()).padStart(2, '0')
            return `${y}-${m}-${day}`
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.maCodeList = []
            this.ids = selection.map(item => item.id)
            selection.forEach(item => {
                this.maCodeList.push({
                    typeId: item.typeId,
                    manageType: 0,
                    leaseType: 0,
                    maId: item.maId,
                    maCode: item.maCode,
                    parentId: this.parentIdTemp,
                    outNum: 1,
                    publishTask: this.publishTask,
                    jiJuType: item.jiJuType,
                    leaseUnit: this.currentRow.leaseUnit,
                    leaseUnitId: this.currentRow.leaseUnitId,
                    leaseProject: this.currentRow.leaseProject,
                    leaseProjectId: this.currentRow.leaseProjectId,
                    taskId: this.currentRow.taskId
                })
            })
            this.single = selection.length != 1
            this.multiple = !selection.length
        },

        getList() {
            this.loading = true
            const params = {
                ...this.queryParams,
                keyWord: this.queryParams.keyWord,
                // startTime: this.queryParams.startTime,
                // endTime: this.queryParams.endTime,
                // pageSize: this.queryParams.pageSize,
                // pageNum: this.queryParams.pageNum,
                hasSign: 1
            }
            console.log("this.addDateRange(params)",this.addDateRange(params));
            getListLeaseQuery(this.addDateRange(params)).then(response => {
                this.typeList = response.data.rows
                this.total = response.data.total
                this.loading = false
            })
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            const end = new Date()
            let start = new Date()
            start.setMonth(start.getMonth() - 1)
            this.queryParams.time = [this.format(end), this.format(end)]
            // this.resetForm('queryForm')
            this.queryParams.keyWord = ''
            this.queryParams.startTime = this.format(end)
            this.queryParams.endTime = this.format(end)
            this.$refs.queryForm.resetFields()
            this.handleQuery()
        },
      /** 导出按钮操作 */
      handleExport() {
        const formatTime = date => {
          const year = date.getFullYear()
          const month = String(date.getMonth() + 1).padStart(2, '0')
          const day = String(date.getDate()).padStart(2, '0')
          const hours = String(date.getHours()).padStart(2, '0')
          const minutes = String(date.getMinutes()).padStart(2, '0')
          const seconds = String(date.getSeconds()).padStart(2, '0')
          return `${year}${month}${day}_${hours}${minutes}${seconds}`
        }

        const currentTime = formatTime(new Date())
        // const params = {
        //   keyWord: this.queryParams.keyWord,
        //   startTime: this.queryParams.startTime,
        //   endTime: this.queryParams.endTime,
        //   pageSize: this.queryParams.pageSize,
        //   pageNum: this.queryParams.pageNum,
        //   hasSign: 1
        // }
        const params = {
            ...this.queryParams,
            keyWord: this.queryParams.keyWord,
            // startTime: this.queryParams.startTime,
            // endTime: this.queryParams.endTime,
            // pageSize: this.queryParams.pageSize,
            // pageNum: this.queryParams.pageNum,
            hasSign: 1
        }
        console.log("this.addDateRange(params)exp",this.addDateRange(params));
        this.download(
          '/material/lease_apply_info/exportLeaseQueryOutRecord',
          { ...params },
          `领料查询数据_${currentTime}.xlsx`
        )
      },
    },

    watch: {
        $route: {
            handler(to) {
                if (to.query.keyWord) {
                    this.queryParams.keyWord = to.query.keyWord
                }
            },
            deep: true,
            immediate: true
        }
    }
}
</script>
<style lang="scss" scoped>
::v-deep.el-table .fixed-width .el-button--mini {
    width: 70px !important;
    margin-bottom: 10px;
}
.is-rotate {
    transform: rotate(-90deg);
}
.print-table {
    table,
    th,
    td {
        border: 1.5px solid black;
        border-collapse: collapse;
    }
}
.my-loading {
    z-index: 99999 !important;
}
</style>
