<template>
  <!-- 基础页面 -->
  <div class="app-container">
    <el-form v-show="showSearch" :model="queryParams" ref="queryForm" size="small" inline @submit.native.prevent>
      <el-form-item label="选择单位" prop="unitId">
        <TreeSelect
          v-model="queryParams.unitId"
          :options="unitList"
          :normalizer="normalizer"
          :show-count="true"
          style="width: 215px"
          :disable-branch-nodes="true"
          noChildrenText="没有数据了"
          noOptionsText="没有数据"
          noResultsText="没有搜索结果"
          placeholder="请选择单位"
          @select="unitChange"
        />
      </el-form-item>

      <el-form-item label="选择工程" prop="projectId">
        <TreeSelect
          v-model="queryParams.projectId"
          :options="proList"
          :normalizer="normalizer"
          :show-count="true"
          style="width: 215px"
          :disable-branch-nodes="true"
          noChildrenText="没有数据了"
          noOptionsText="没有数据"
          noResultsText="没有搜索结果"
          placeholder="请选择工程"
          @select="proChange"
        />
      </el-form-item>
      <el-form-item label="推送月份" prop="month">
        <el-date-picker
          v-model="queryParams.month"
          type="month"
          :clearable="false"
          placeholder="请选择月份"
          value-format="yyyy-MM"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="提交状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 240px">
          <el-option v-for="item in pushList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>

      <!-- <el-form-item style="display: flex; justify-content: flex-end"> -->
      <!-- 表单按钮 -->
      <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-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出数据</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" size="mini" :disabled="selectionList.length == 0" @click="submit">提 交</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      :data="tableList"
      fit
      highlight-current-row
      show-summary
      :summary-method="getSummaries"
      style="width: 100%"
      @selection-change="selectionChange"
    >
      <!-- 多选 -->
      <el-table-column type="selection" width="65" align="center" :selectable="row => row.pushStatus == 0" />
      <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"
        show-overflow-tooltip
        :key="index"
        :label="column.label"
        :prop="column.prop"
        align="center"
      >
        <!-- 插槽 -->
        <template v-slot="{ row }" v-if="column.prop == 'leaseMoney'">
          <span style="color: #409eff; cursor: pointer" @click="openDialog(row, 1)">{{ row.leaseMoney }}</span>
        </template>
        <template v-slot="{ row }" v-else-if="column.prop == 'lostMoney'">
          <span style="color: #409eff; cursor: pointer" @click="openDialog(row, 2)">{{ row.lostMoney }}</span>
        </template>
        <template v-slot="{ row }" v-else-if="column.prop == 'scrapMoney'">
          <span style="color: #409eff; cursor: pointer" @click="openDialog(row, 3)">{{ row.scrapMoney }}</span>
        </template>
        <template v-slot="{ row }" v-else-if="column.prop == 'pushStatus'">
          <span v-if="row.pushStatus == 0">未推送</span>
          <span v-else-if="row.pushStatus == 1">已推送</span>
          <span v-else-if="row.pushStatus == 2">已退回</span>
          <span v-else-if="row.pushStatus == 3">进行中</span>
        </template>
      </el-table-column>
      <!-- 操作 -->
    </el-table>

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

    <!-- 弹框 -->
    <el-dialog title="查看" :visible.sync="dialogVisible" width="70%">
      <el-form ref="dialogForm" :model="dialogForm" label-width="80px" size="small" inline @submit.native.prevent>
        <el-form-item label="" prop="modelName">
          <el-input v-model="dialogForm.modelName" placeholder="请输入机具名称" clearable style="width: 240px" />
        </el-form-item>
        <el-form-item label="" prop="typeName">
          <el-input v-model="dialogForm.typeName" placeholder="请输入规格型号" clearable style="width: 240px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="getDiaList">查询</el-button>
          <el-button icon="el-icon-refresh" @click="resetDialog">重置</el-button>
          <el-button type="warning" icon="el-icon-download" @click="handleDiaExport">导出数据</el-button>
        </el-form-item>
      </el-form>

      <el-table
        :data="dialogTableList"
        fit
        highlight-current-row
        show-summary
        :summary-method="getDiaSummaries"
        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"
          show-overflow-tooltip
          :key="index"
          :label="column.label"
          :prop="column.prop"
          align="center"
        ></el-table-column>
      </el-table>
          <!-- 分页 -->
        <pagination
          v-show="dialogTotal > 0"
          :total="dialogTotal"
          :page.sync="dialogForm.pageNum"
          :limit.sync="dialogForm.pageSize"
          @pagination="getDiaList"
        />
    </el-dialog>
  </div>
</template>

<script>
import { getProjectList, getUnitList, getAgreementInfoById } from '@/api/back/index.js'
import { getCostPushCheckList, getCostPushCheckListCount, checkData,getCostPushLeaseListApi } from '@/api/costPush/costPush'
import TreeSelect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  components: { TreeSelect },
  data() {
    return {
      showSearch: true,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        unitId: null,
        projectId: null,
        agreementId: '',
        agreementCode: '',
        month: new Date().getFullYear() + '-' + (new Date().getMonth() + 1),
        isSend: null
      },
      unitList: [], // 单位
      proList: [], // 工程
      pushList: [
        { label: '未推送', value: '0' },
        { label: '已推送', value: '1' },
        { label: '已退回', value: '2' },
        { label: '进行中', value: '3' }
      ], // 工程状态
      total: 0, // 总条数
      // 表头
      tableColumns: [
        { label: '单位名称', prop: 'unitName' },
        { label: 'i8工程编号', prop: 'pc_no' },
        { label: '工程名称', prop: 'projectName' },
        { label: '推送月份', prop: 'month' },
        { label: '租赁费用', prop: 'leaseMoney' },
        { label: '丢失费用', prop: 'lostMoney' },
        { label: '报废费用', prop: 'scrapMoney' },
        { label: '合计费用', prop: 'money' },
        { label: '推送状态', prop: 'pushStatus' },
        { label: '推送备注', prop: 'pushRemark' }
      ],
      // 表格数据
      tableList: [],
      // 合计
      totalData: {
        leaseMoney: 0,
        scrapMoney: 0,
        lostMoney: 0,
        money: 0
      },
      selectionList: [], // 选中行
      // 弹窗数据
      costIndex: 1,
      dialogVisible: false,
      dialogForm: {
        name: '',
        type: '',
        pageNum: 1,
        pageSize: 10
      },
      dialogTotal: 0,
      dialogTableList: [],
      dialogColumns: [],
      dialogColumns1: [
        { label: '机具名称', prop: 'typeName' },
        { label: '规格型号', prop: 'typeModelName' },
        { label: '领料时间', prop: 'leaseTime' },
        { label: '退料时间', prop: 'backTime' },
        { label: '租赁天数', prop: 'leaseDays' },
        { label: '租赁价格', prop: 'leasePrice' },
        { label: '租赁数量', prop: 'num' },
        { label: '租赁费用', prop: 'costs' },
        { label: '费用结算时间', prop: 'settleTime' }
      ],
      dialogColumns2: [
        { label: '机具名称', prop: 'typeName' },
        { label: '规格型号', prop: 'typeModelName' },
        { label: '单价', prop: 'price' },
        { label: '丢失数量', prop: 'num' },
        { label: '丢失费用', prop: 'costs' },
        { label: '费用结算时间', prop: 'settleTime' }
      ],
      dialogColumns3: [
        { label: '机具名称', prop: 'typeName' },
        { label: '规格型号', prop: 'typeModelName' },
        { label: '报废数量', prop: 'num' },
        { label: '报废费用', prop: 'costs' },
        { label: '费用结算时间', prop: 'settleTime' }
      ]
    }
  },
  created() {
    this.GetUnitData()
    this.GetProData()
    this.getList()
  },
  methods: {
    // 查询
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置
    handleReset() {
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.$refs.queryForm.resetFields()
      this.getList()
      this.GetUnitData()
      this.GetProData()
    },
    // 获取列表
    async getList() {
      console.log('列表-查询', this.queryParams)
      const loading = this.$loading({ text: '加载中...' })
      try {
        const params = { ...this.queryParams }
        const res = await getCostPushCheckList(params)
        console.log('🚀 ~ 获取列表 ~ res:', res)
        this.tableList = res.rows
        this.total = res.total
        const res2 = await getCostPushCheckListCount()
        this.totalData = res2.data
        loading.close()
      } catch (error) {
        console.log('🚀 ~ 获取列表 ~ error:', error)
        this.tableList = []
        this.total = 0
        loading.close()
      }
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },
    // 多选
    selectionChange(val) {
      console.log('selectionChange', val)
      this.selectionList = val
    },
    selectable(row) {
      console.log('🚀 ~ selectable ~ row:', row)
      if (row.pushStatus != 0) {
        return false
      } else {
        return true
      }
    },
    // 合计
    getSummaries() {
      const sums = []
      sums[0] = '合计'
      sums[6] = this.totalData.leaseMoney
      sums[7] = this.totalData.scrapMoney
      sums[8] = this.totalData.lostMoney
      sums[9] = this.totalData.money

      return sums
    },
    // 获取 单位 列表数据
    async GetUnitData() {
      try {
        const res = await getUnitList({})
        this.unitList = res.data
        this.getAgreementInfo()
      } catch (error) {
        console.log('🚀 ~ GetUnitData ~ error:', error)
      }
    },
    unitChange(val) {
      setTimeout(() => {
        this.queryParams.projectId = null
        this.queryParams.agreementId = null
        this.queryParams.agreementCode = null
        this.GetProData()
      }, 300)
    },
    // 获取 工程名称 列表数据
    async GetProData() {
      const params = {
        unitId: this.queryParams.unitId
      }
      try {
        const res = await getProjectList(params)
        this.proList = res.data
        this.getAgreementInfo()
      } catch (error) {
        console.log('🚀 ~ GetProData ~ error:', error)
      }
    },
    proChange(val) {
      setTimeout(() => {
        this.GetUnitData()
      }, 500)
    },
    // 获取 协议id
    async getAgreementInfo() {
      if (this.queryParams.unitId && this.queryParams.projectId) {
        const params = {
          unitId: this.queryParams.unitId,
          projectId: this.queryParams.projectId
        }
        try {
          const res = await getAgreementInfoById(params)
          console.log('🚀 ~ 协议id ~ res:', res)
          if (res.data && res.data.agreementId) {
            this.queryParams.agreementId = res.data.agreementId
            this.queryParams.agreementCode = res.data.agreementCode
          } else {
            this.$message.error('当前单位和工程无协议！')
            this.queryParams.unitId = null
            this.queryParams.projectId = null
            this.GetUnitData()
            this.GetProData()
          }
        } catch (error) {
          console.log('🚀 ~ getAgreementInfo ~ error:', error)
        }
      }
    },
    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}`
    },
    // 导出数据
    handleExport() {
      try {
        let fileName = `机具费用推送_${this.formatTime(new Date())}.xLsx`
        let url = '/material/backstage/costPush/exportPushCheck'
        const params = { ...this.queryParams }
        console.log('🚀 ~ 导出 ~ params:', params)
        this.download(url, params, fileName)
      } catch (error) {
        console.log('导出数据失败', error)
      }
    },
    submit() {
      // 弹框确认
      this.$confirm('是否确认提交？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          try {
            const cheks = JSON.stringify(this.selectionList)
            checkData(cheks).then(res => {
              // 确定
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.getList()
            })
          } catch (error) {
            console.log('🚀 ~ .then ~ error:', error)
          }
        })
        .catch(() => {
          // 取消
        })
    },
    // 弹框
    openDialog(row, type) {
      this.costIndex = type
      this.dialogColumns = []
      if (type === 1) {
        this.dialogColumns = this.dialogColumns1
      } else if (type === 2) {
        this.dialogColumns = this.dialogColumns2
      } else if (type === 3) {
        this.dialogColumns = this.dialogColumns3
      }
      this.getDiaList()
      setTimeout(() => {
        this.dialogVisible = true
      }, 200)
    },
    // 弹框列表
    async getDiaList() {
      let res = null
      const params = { ...this.dialogForm }
      try {
        if (this.costIndex === 1) {
          res = await getCostPushLeaseListApi(params)
          this.dialogTableList = res.data
        }
        //  else if (this.costIndex === 2) {
        //   res = await
        // } else if (this.costIndex === 3) {
        //   res = await
        // }
      } catch (error) {
        console.log('🚀 ~ getDiaList ~ error:', error)
      }
    },
    // 弹框重置
    resetDialog() {
      this.dialogForm = {
        modelName: '',
        typeName: ''
      }
      this.getDiaList()
    },
    // 弹框合计
    getDiaSummaries(param) {
      const { columns, data } = param
      const sums = []
      sums[0] = '合计'
      let total = 0
      data.forEach((column, index) => {
        total += Number(column.costs)
      })
      if (this.costIndex == 1) {
        sums[8] = total
      } else if (this.costIndex == 2) {
        sums[5] = total
      } else if (this.costIndex == 3) {
        sums[4] = total
      }
      return sums
    },
    // 弹框导出数据
    handleDiaExport() {
      // 提示
      this.$message({
        type: 'warning',
        message: '导出功能开发中，敬请期待！'
      })
      try {
        let fileName = `数据_${this.formatTime(new Date())}.xLsx`
        let url = ''
        if (this.costIndex == 1) {
          url = ''
        } else if (this.costIndex == 2) {
          url = ''
        } else if (this.costIndex == 3) {
          url = ''
        }
        const params = { ...this.dialogForm }
        console.log('🚀 ~ 导出 ~ params:', params)
        // this.download(url, params, fileName)
      } catch (error) {
        console.log('导出数据失败', error)
      }
    }
  }
}
</script>

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