<template>
  <!-- 基础页面 -->
  <div class="app-container">
    <el-form v-show="showSearch" :model="queryParams" ref="queryForm" size="small" inline @submit.native.prevent label-width="100px">
      <!-- 日期范围 -->
      <el-form-item label="退料时间" prop="startTime">
        <el-date-picker
          v-model="queryParams.startTime"
          type="date"
          placeholder="开始日期"
          :clearable="false"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          @change="() => queryParams.endTime = ''"
          style="width: 130px"
        />
      </el-form-item>
      <el-form-item label="">-</el-form-item>
      <el-form-item label="" prop="endTime">
        <el-date-picker
          v-model="queryParams.endTime"
          type="date"
          placeholder="结束日期"
          clearable
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          :picker-options="{ disabledDate: (t) => t.getTime() < new Date(queryParams.startTime).getTime() - 86400000}"
          style="width: 130px"
        />
      </el-form-item>
      <el-form-item label="分公司" prop="impUnitName">
        <el-select
          v-model="queryParams.impUnitName"
          placeholder="请选择分公司"
          clearable
          filterable
          style="width: 240px"
          @change="handleDepartChange"
        >
          <el-option
            v-for="item in impUnitOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="退料工程" prop="proName">
        <el-select
          v-model="queryParams.proName"
          placeholder="请选择退料工程"
          clearable
          filterable
          style="width: 240px"
        >
          <el-option
            v-for="item in proOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="退料单位" prop="unitName">
        <el-input
          v-model="queryParams.unitName"
          placeholder="请输入退料单位"
          clearable
          maxlength="50"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="物资名称" prop="typeName">
        <el-select
          v-model="queryParams.typeName"
          placeholder="请选择物资名称"
          clearable
          filterable
          style="width: 240px"
        >
          <el-option
            v-for="item in materialNameList"
            :key="item.value"
            :label="item.label"
            :value="item.label"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="退料人" prop="backPerson">
        <el-input
          v-model="queryParams.backPerson"
          placeholder="请输入退料人"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 240px"
        />
      </el-form-item>

      <el-form-item label="退料单号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入退料单号"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 240px"
        />
      </el-form-item>


      <!-- <el-form-item label="关键字" prop="keyWord">
        <el-input
          v-model="queryParams.keyWord"
          placeholder="请输入关键字"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 240px"
        />
      </el-form-item> -->

      <!-- 表单按钮 -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table :data="tableList" fit highlight-current-row style="width: 100%" :max-height="650">
      <!-- 多选 -->
      <!-- <el-table-column type="selection" width="55" align="center" @selection-change="selectionChange" /> -->
      <el-table-column
        type="index"
        width="55"
        label="序号"
        align="center"
        :index="index => (queryParams.pageNum - 1) * queryParams.pageSize + index + 1"
      />
      <el-table-column
        v-for="(column, index) in tableColumns"
        :key="index"
        :label="column.label"
        :prop="column.prop"
        align="center"
      ></el-table-column>
      <!-- 操作 -->
      <el-table-column label="操作" align="center" width="220">
        <template slot-scope="{ row }">
          <el-button type="text" size="mini" icon="el-icon-zoom-in" @click="handleView(row)">查看</el-button>
          <el-button
            v-if="row.isZz == 0"
            type="text"
            size="mini"
            icon="el-icon-document"
            style="color: #67c23a"
            @click="handleLld(row)"
          >
            退料单
          </el-button>
          <el-button
            v-if="row.isZz != 0"
            type="text"
            size="mini"
            icon="el-icon-document"
            @click="handleDialog(row.directId)"
          >
            直转单
          </el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 退料单 -->
    <dialogFormByClz :dialogTitle="title" :isShowFlag.sync="isShowOneFlag" :priKey="priKey" :rowObj="rowObj"></dialogFormByClz>

    <!-- 弹框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%">
      <el-table :data="dialogList" fit highlight-current-row style="width: 100%">
        <el-table-column
          type="index"
          width="55"
          label="序号"
          align="center"
          :index="index => (dialogForm.pageNum - 1) * dialogForm.pageSize + index + 1"
        />
        <el-table-column
          v-for="(column, index) in dialogColumns"
          :key="index"
          :label="column.label"
          :prop="column.prop"
          :width="column.width"
          align="center"
        ></el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="dlgTotal > 0"
        :total="dlgTotal"
        :page.sync="dialogForm.pageNum"
        :limit.sync="dialogForm.pageSize"
        @pagination="getDetailsList"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>

    <!-- 直转单 -->
    <StraightforwardBills ref="straightforwardBills" />
  </div>
</template>

<script>
import { getBackTotalListApi, getBackDetailsListApi,
  getImpUnitListApi, getDepartListByImpUnitApi, getProListByDepartApi,
 } from '@/api/materialsStation'
import dialogFormByClz from '@/views/materialsStation/equipment/totalReturnRecord/dialogFormByClz.vue'
import {getMaterialTypeList} from "@/api/ma/device";
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import StraightforwardBills from '@/views/materialsStation/straight/straightTransferReview/components/StraightforwardBills.vue'
import {formatTime} from "@/utils/bonus";

export default {
  name: 'TotalReturnRecord',
  components: { dialogFormByClz,Treeselect,StraightforwardBills, StraightforwardBills },
  data() {
    return {
      showSearch: true,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyWord: '', // 关键字
        proStatus: '', // 状态
        timeRange: [], // 日期范围
        startTime: '', // 开始时间
        endTime: '', // 结束时间
        impUnitName: '', // 分公司
        unitName: '', // 退料单位
        proName: '', // 退料工程
        typeName: '', // 物资名称
        backPerson: '', // 退料人
        code: '' // 退料单号
      },
      statusOptions: [], // 工程状态
      total: 0, // 总条数
      // 表头
      tableColumns: [
        { label: '分公司', prop: 'impUnitName' },
        { label: '退料单位', prop: 'unitName' },
        { label: '退料工程', prop: 'proName' },
        { label: '退料物资类型', prop: 'typeName' },
        { label: '退料人', prop: 'backPerson', width: 90 },
        { label: '退料时间', prop: 'backTime', width: 100 },
        { label: '退料单号', prop: 'code' }
      ],
      // 表格数据
      tableList: [],
      dlgTotal: 0, // 弹框总条数
      dialogTitle: '查看',
      dialogVisible: false,
      dialogForm: {
        pageNum: 1,
        pageSize: 10,
        keyWord: '', // 关键字
        parentId: null, // 父级id
      },
      dialogColumns: [
        { label: '类型名称', prop: 'typeCode' },
        { label: '物资名称', prop: 'typeName' },
        { label: '规格型号', prop: 'modelCode' },
        { label: '计量单位', prop: 'unitNames' },
        { label: '预退数量', prop: 'backNum' },
        { label: '退料数量', prop: 'backNum' },
        { label: '备注', prop: 'remark' }
      ],
      dialogList: [],
      deptList: [], // 分公司
      unitList: [], // 退料单位
      proList: [], // 退料工程
      typeModelList: [] ,// 物资名称
      materialNameList: [], // 物资名称
      impUnitOptions: [],   // 分公司下拉
      proOptions: [],       // 工程下拉

      //退料单
      isShowOneFlag: false,
      rowObj: {},
      priKey: '',
      title: '',
    }
  },
  created() {
    const end = new Date()
    let start = new Date()
    start.setMonth(start.getMonth() - 1)
    this.queryParams.timeRange = [this.format(start), this.format(end)]
    this.queryParams.startTime = this.queryParams.timeRange[0]
    this.queryParams.endTime = this.queryParams.timeRange[1]
    this.getImpUnitOptions()
    this.handleDepartChange()
    this.getDeviceType()
    this.getList()
  },
  methods: {
    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}`
    },

    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },

    /** 获取分公司下拉 */
    async getImpUnitOptions() {
      try {
        const res = await getImpUnitListApi() // 调后台接口
        this.impUnitOptions = res.data.map(item => ({
          label: item.impUnitName,   // 这里根据实际字段替换
          value: item.impUnitName
        }))
      } catch (e) {
        console.error('获取分公司下拉失败:', e)
      }
    },

    async handleDepartChange() {
      this.queryParams.proName = null // 清空工程已选
      this.proOptions = []            // 清空原有下拉

      try {
        // 同时传入分公司和项目部参数
        const params = {
          impUnitName: this.queryParams.impUnitName, // 分公司名称
          proName: this.queryParams.proName,
        }
        const res = await getProListByDepartApi(params)
        this.proOptions = res.data.map(item => ({
          label: item.proName,   // 工程名称字段
          value: item.proName
        }))
      } catch (e) {
        console.error('获取工程下拉失败:', e)
      }
    },

    getDeviceType() {
      getMaterialTypeList({ level: 3, skipPermission: 1 }).then(response => {
        let matNameRes = response.data
        this.materialNameList = matNameRes.map((item) => {
          return {
            label: item.typeName,
            value: item.typeId
          }
        })
      })
    },

    // 查询
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置
    handleReset() {
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.$refs.queryForm.resetFields()
      const end = new Date()
      let start = new Date()
      start.setMonth(start.getMonth() - 1)
      this.queryParams.timeRange = [this.format(start), this.format(end)]
      this.queryParams.startTime = this.queryParams.timeRange[0]
      this.queryParams.endTime = this.queryParams.timeRange[1]
      this.getList()
    },
    // 获取列表
    async getList() {
      console.log('列表-查询', this.queryParams)
      const loading = this.$loading({ text: '加载中...' })
      // this.queryParams.startTime = this.queryParams.timeRange ? this.queryParams.timeRange[0] : ''
      // this.queryParams.endTime = this.queryParams.timeRange ? this.queryParams.timeRange[1] : ''
      try {
        const params = { ...this.queryParams }
        const res = await getBackTotalListApi(params)
        console.log('🚀 ~ 获取列表 ~ res:', res)
        this.tableList = res.data.rows
        this.total = res.data.total
        loading.close()
      } catch (error) {
        console.log('🚀 ~ 获取列表 ~ error:', error)
        this.tableList = []
        this.total = 0
        loading.close()
      }
    },
    // 获取详情列表
    async getDetailsList() {
      try {
        const res = await getBackDetailsListApi({ ...this.dialogForm })
        console.log('🚀 ~ 获取详情列表 ~ res:', res)
        this.dialogList = res.data.rows
        this.dlgTotal = res.data.total
      } catch (error) {
        console.log('🚀 ~ 获取详情列表 ~ error:', error)
        this.dialogList = []
        this.dlgTotal = 0
      }
    },
    // 查看
    handleView(row) {
      console.log('查看', row)
      this.dialogTitle = '查看'
      this.dialogVisible = true
      setTimeout(() => {
        this.dialogForm.parentId = row.id
        this.getDetailsList()
      }, 100)
    },
    // 退料单
    handleLld(row) {
        this.isShowOneFlag = true
        this.rowObj = row
    },
    handleDialog(id) {
      this.$refs.straightforwardBills.openDialog(id, 2)
    },
    // 导出数据
    handleExport() {
      // // 提示
      // this.$message({
      //   type: 'warning',
      //   message: '导出功能开发中，敬请期待！'
      // })
      try {
        let fileName = `材料站点退料记录_${formatTime(new Date())}.xlsx`
        let url = ''
        const params = { ...this.queryParams }
          this.download(
              'material/material_back_apply_info/exportBackInfoExcl',
              {
                  ...params,
              },
              fileName
          )
        console.log('🚀 ~ 导出 ~ params:', params)
        // this.derive(url, params, fileName)
        // this.download(url, params, fileName)
      } catch (error) {
        console.log('导出数据失败', error)
      }
    }
  }
}
</script>

<style lang="scss" scoped></style>
