<template>
  <div class="app-container" id="costApplyList">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="80px">
      <el-form-item label="分公司" prop="impUnitName">
        <el-select
          v-model="queryParams.impUnitName"
          placeholder="请选择分公司"
          clearable
          filterable
          style="width: 240px"
          @change="handleImpUnitChange"
        >
          <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="departName">
        <el-select
          v-model="queryParams.departName"
          placeholder="请选择项目部"
          clearable
          filterable
          style="width: 240px"
          @change="handleDepartChange"
        >
          <el-option
            v-for="item in departOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
        <el-form-item label="结算工程">
          <el-select
          v-model="queryParams.projectId"
          placeholder="请选择工程"
          clearable
          filterable
          style="width: 240px"
          @change="loadTeamList"
        >
          <el-option
            v-for="item in projectList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        </el-form-item>

        <el-form-item label="结算班组">
          <el-select
            v-model="unitIds"
            placeholder="请选择班组"
            clearable
            filterable
            multiple
            style="width: 240px"
            @change="changeTeamId"
          >
            <el-option
              v-for="item in teamList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
        </el-select>
        </el-form-item>
      <el-form-item prop="agreementCode">
        <el-tooltip content="协议编号" placement="top" :disabled="!queryParams.agreementCode">
          <template #content>
            {{ queryParams.agreementCode }}
          </template>
          <el-input v-model="queryParams.agreementCode" placeholder="请输入协议号" clearable disabled/>
        </el-tooltip>
      </el-form-item>
      <el-form-item prop="sltStatus" label="结算状态">
        <el-select v-model="queryParams.sltStatus" placeholder="请选择结算状态" clearable filterable>
          <el-option
            v-for="dict in dict.type.cost_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></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 style="display: none;" type="primary" plain size="mini" @click="handleApplyList">批量结算</el-button>
        <el-button type="success" icon="el-icon-plus" size="mini" @click="goToSettlement">新增结算</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="tableList" @selection-change="handleSelectionChange" :max-height="650">
      <el-table-column
        type="selection"
        width="55"
        align="center"
        :selectable="row => row.sltStatus == 0 || row.sltStatus == 3"
      />
      <el-table-column label="序号" align="center" width="80" type="index">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="协议号" align="center" prop="agreementCode" :show-overflow-tooltip="true" width="150"/>
      <el-table-column label="分公司" align="center" prop="impUnitName" width="200" />
      <el-table-column label="项目部" align="center" prop="departName" width="200" />
      <el-table-column label="结算工程" align="center" prop="projectName" width="200" />
      <el-table-column label="结算班组" align="center" prop="unitName" width="150" />
      <el-table-column label="合计费用（元）" align="center" prop="costs" :show-overflow-tooltip="true" width="200">
        <template slot-scope="scope" v-if="scope.row.costs != null && scope.row.costs != ''">
          {{ scope.row.costs.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column label="结算状态" align="center" prop="sltStatus" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.cost_status" :value="scope.row.sltStatus" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            style="display: none"
            disabled="disabled"
            size="mini"
            type="hi"
            icon="el-icon-edit"
            @click="handleApply(scope.row)"
            v-if="scope.row.sltStatus == '0' || scope.row.sltStatus == '3'"
          >
            结算申请
          </el-button>

          <el-button type="primary" plain size="mini" @click="openPrintDialog(scope.row)">协议书</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"
    />

    <!-- 协议单弹窗 -->
    <el-dialog :visible.sync="openPrint" width="1100px" append-to-body>
      <div id="checkId">
        <div style="height: 600px; overflow-y: scroll">
          <vue-easy-print tableShow ref="remarksPrintRef" class="print">
            <div style="text-align: center; font-weight: 600; font-size: 16px">机具设备有偿使用费结算协议书</div>
            <div class="info" style="margin-top: 10px; display: flex; flex-wrap: wrap">
              <div class="item" style="width: 65%; flex-shrink: 0; margin-bottom: 5px; font-size: 14px"></div>
              <div class="item" style="width: 35%; flex-shrink: 0; margin-bottom: 5px; font-size: 14px">
                <span>协议号：{{ agreementContent.agreementCode }}</span>
              </div>
            </div>
            <div class="tabelColumn">
              <div class="columnLabel" style="width: 20%">工程名称：</div>
              <div class="columnContent" style="width: 80%">{{ agreementContent.projectName }}</div>
            </div>
            <div class="tabelColumn">
              <div class="columnLabel" style="width: 20%">承租单位：</div>
              <div class="columnContent" style="width: 40%">{{ agreementContent.unitName }}</div>
              <div class="columnLabel" style="width: 10%; border-left: 1px solid #9c9c9c">日期：</div>
              <div class="columnContent" style="width: 30%">{{ agreementContent.applyTime || newData }}</div>
            </div>
            <div class="tabelColumn">
              <div class="columnLabel" style="width: 100%">结算项目及金额(元)</div>
            </div>
            <div class="tabelColumn">
              <div class="columnLabel" style="width: 60%">一、施工机具有偿使用费：</div>
              <div class="columnContent" style="width: 40%">￥ {{ Number(agreementContent.leaseCost).toFixed(2) }}</div>
            </div>
            <div class="tabelColumn">
              <div class="columnLabel" style="width: 60%">二、施工机具维修费：</div>
              <div class="columnContent" style="width: 40%">￥ {{ Number(agreementContent.repairCost).toFixed(2) }}</div>
            </div>
            <div class="tabelColumn">
              <div class="columnLabel" style="width: 60%">三、施工机具丢失费：</div>
              <div class="columnContent" style="width: 40%">￥ {{ Number(agreementContent.loseCost).toFixed(2) }}</div>
            </div>
            <div class="tabelColumn">
              <div class="columnLabel" style="width: 60%">四、施工机具损坏赔偿费：</div>
              <div class="columnContent" style="width: 40%">￥ {{ Number(agreementContent.scrapCost).toFixed(2) }}</div>
            </div>
            <div class="tabelColumn">
              <div class="columnLabel" style="width: 60%">五、施工机具租赁减免费：</div>
              <div class="columnContent" style="width: 40%">￥ {{ Number(agreementContent.reductionCost).toFixed(2) }}</div>
            </div>
            <div class="tabelColumn">
              <div class="columnLabel" style="width: 20%">费用合计金额（大写）：</div>
              <div class="columnContent" style="width: 40%">{{ agreementContent.costAllUpper }}</div>
              <div class="columnContent" style="width: 40%">￥ {{ Number(agreementContent.costAll).toFixed(2) }}</div>
            </div>
            <div class="tabelColumn" style="border: 1px solid #9c9c9c;">
              <div class="columnLabel" style="width: 20%">说明：</div>
              <div class="columnContent" style="width: 80%">本协议一式两份，甲方一份，乙方一份，经双方签字后生效。</div>
            </div>

            <div class="fillIn" style="margin-top: 20px; display: flex; justify-content: space-between">
              <div class="item" style="width: 33%">
                <div>
                  <span>部门负责人：</span>
             
                </div>
              </div>

              <div class="item" style="width: 33%">
                <div>
                  <span>承租负责人：</span>
                </div>
              </div>

              <div class="item" style="width: 33%">
                <div>
                  <span>核算员：</span>
                </div>
              </div>
            </div>
          </vue-easy-print>
        </div>
      </div>

      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="print">打 印</el-button>
        <el-button @click="openPrint = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
   getClzProjectListApi,getClzTeamListApi,getImpUnitListApi,getDepartListByImpUnitApi
} from '@/api/materialsStation'
import { getTeamList } from '@/api/materialsStation/auth.js'
import {  getClzSltAgreementInfo, getClzProjectListByUnitIds, getClzAgreementInfoById, getClzSltInfo} from '@/api/cost/cost'
import { toChineseAmount } from '@/utils/bonus.js'
import vueEasyPrint from 'vue-easy-print'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import printJS from 'print-js'
export default {
  name: 'CostApplyList',
  dicts: ['cost_status'],
  components: { Treeselect, vueEasyPrint },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 班组数据
      teamList: [],
      // 工程数据
      projectList: [],
      unitIds: [],
      // 表格数据
      tableList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sltStatus: '',
        isCommit: '',
        unitId: null,
        projectId: null,
        agreementId: [],
        agreementCode: '',
        impUnitName: '', // 分公司
        departName: '' // 项目部
      },
      impUnitOptions: [], // 分公司下拉选项
      departOptions: [], // 项目部下拉选项
      openPrint: false,
      // 协议书内容
      agreementContent: {
        agreementCode: '',
        projectName: '',
        unitName: '',
        leaseCost: '', // 租赁费用
        repairCost: '', // 维修费用
        loseCost: '', // 丢失费用
        scrapCost: '', // 报废费用
        reductionCost: '', // 减免费用
        costAll: '', // 合计费用
        costAllUpper: '' // 合计费用大写
      },
      newData: new Date().toISOString().split('T')[0]
    }
  },
  created() {
    // this.loadProjectList()
    // this.GetProData()
    this.getList()
    this.getImpUnitOptions()
    this.handleImpUnitChange()
    this.handleDepartChange()
  },
  methods: {
    /** 获取分公司下拉 */
    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 handleImpUnitChange() {
      this.queryParams.departName = null // 清空项目部已选
      this.departOptions = []            // 清空原有下拉

      try {
        const params = {
          impUnitName: this.queryParams.impUnitName, // 分公司名称
        }
        const res = await getDepartListByImpUnitApi(params)
        this.departOptions = res.data.map(item => ({
          label: item.departName,   // 项目部名称字段
          value: item.departName
        }))
      } catch (e) {
        console.error('获取项目部下拉失败:', e)
      }
    },
    /** 项目部选择变化，加载工程 */
    async handleDepartChange() {
      this.queryParams.projectId = null // 清空工程已选
      this.projectList = []            // 清空原有下拉

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

    async loadProjectList() {
      try {
        const params = {
          impUnitName: this.queryParams.impUnitName, // 分公司名称
          departName: this.queryParams.departName, // 项目部名称
        }
        const res = await getClzProjectListApi(params)
        if (res.code === 200) {
          // this.projectList = response.data || []
          this.projectList = res.data.map(item => ({
          label: item.proName,   // 工程名称字段
          value: item.proId,
          projectId: item.projectId
        }))
        }
      } catch (error) {
        console.error('获取工程列表失败:', error)
        this.$message.error('获取工程列表失败')
      }
    },
    // 获取 工程名称 列表数据
    async loadTeamList() {
      try {
        this.queryParams.agreementId = null
        this.queryParams.agreementCode = null
        const params = {
          proId: this.queryParams.projectId,
        }
        const res = await getClzTeamListApi(params)
        if (res.code === 200) {
          // this.teamList = response.data || []
          this.teamList = res.data.map(item => ({
          label: item.unitName,   // 工程名称字段
          value: item.unitId
        }))
        }
      } catch (error) {
        console.error('获取班组列表失败:', error)
        this.$message.error('获取班组列表失败')
      }

    },

    async changeTeamId() {
      await this.getAgreementInfo()
    },

        // 获取 协议id
    async getAgreementInfo() {
      if (this.unitIds && this.unitIds.length > 0 && this.queryParams.projectId) {
        const params = {
          unitIds: this.unitIds,
          projectId: this.queryParams.projectId
        }
        const res = await getClzAgreementInfoById(params)
        console.log(res)
        if (!res.data && res.data.some(item => !item.agreementId)) {
          this.$message.error('当前单位和工程无协议！')
          this.unitIds = []
          this.queryParams.projectId = null
          this.loadProjectList()
        } else {
          this.queryParams.agreementId = res.data.map(item => item.agreementId)
          this.queryParams.agreementCode = res.data.map(item => item.agreementCode).join(',')
        }
      }
    },

    /** 查询列表 */
    getList() {
      this.loading = true
      const params = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        projectId: this.queryParams.projectId,
        sltStatus: this.queryParams.sltStatus,
        // ...this.queryParams,
        unitIds: this.unitIds,
        impUnitName: this.queryParams.impUnitName, // 分公司名称
        departName: this.queryParams.departName, // 项目部名称
      }
      getClzSltAgreementInfo(params).then(response => {
        this.tableList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.unitIds = []
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        sltStatus: '',
        isCommit: '',
        unitId: null,
        projectId: null,
        agreementId: [],
        agreementCode: ''
      }
      this.teamList = []
      this.resetForm('queryForm')
      this.handleImpUnitChange()
      this.handleDepartChange()
      this.handleQuery()
    },
    //结算申请
    handleApply(row) {
      let arr = []
      arr.push(row)
      this.$emit('goDetail', JSON.stringify(arr))
    },
    handleApplyList() {
      if (this.ids.length < 1) {
        this.$message.error('请勾选需要结算的数据！')
        return
      }
      if (this.ids.length > 0) {
        let arr = this.ids
        this.$emit('goDetail', JSON.stringify(arr))
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    async openPrintDialog(row) {
      this.openPrint = true
      try {
        row.unitIds = (row.unitId + '').split(',');
        const res = await getClzSltInfo(row)
        console.log('🚀 ~ openPrintDialog ~ res:', res)
        if (!res.data) return
        this.agreementContent = res.data[0]
        this.agreementContent.agreementCode = row.agreementCode
        this.agreementContent.costAll =
          Number(res.data[0].leaseCost) +
          Number(res.data[0].repairCost) +
          Number(res.data[0].scrapCost) +
          Number(res.data[0].loseCost) -
          Number(res.data[0].reductionCost)
        // costAllUpper 中文大写
        this.agreementContent.costAllUpper = toChineseAmount(this.agreementContent.costAll.toFixed(2))
      } catch (error) {
        console.log('🚀 ~ openPrintDialog ~ error:', error)
      }
    },
    //维修任务单打印
    print() {
      this.$refs.remarksPrintRef.print()
      //   printJS({
      //     printable: 'checkId',
      //     type: 'html',
      //     targetStyles: ['*'],
      //     maxWidth:'1400'
      //     // 其他配置选项
      //   });
    },
    /** 新增结算按钮操作 */
    goToSettlement() {
      this.$router.push('/settlement/add')
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep.el-table .fixed-width .el-button--mini {
  width: 80px !important;
  margin-bottom: 10px;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.tabelColumn {
  width: 1000px;
  height: 50px;
  display: flex;
  align-items: center;
  border: 1px solid #9c9c9c;
  // margin-bottom: 1px;
  border-bottom: none;
}
.columnLabel {
  height: 50px;
  line-height: 50px;
  text-align: center;
  border-left: none;
}
.columnContent {
  height: 50px;
  line-height: 50px;
  text-align: center;
  border-left: 1px solid #9c9c9c;
}
</style>
