<template>
  <div class="app-container" id="costApplyList">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item prop="unitIds">
        <treeselect
          v-model="queryParams.unitId"
          :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="projectIds">
        <treeselect
          v-model="queryParams.projectId"
          :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="agreementCode">
        <el-input v-model="queryParams.agreementCode" placeholder="请输入协议号" clearable disabled />
      </el-form-item>
      <el-form-item prop="sltStatus">
        <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"
            v-if="dict.value !== '0'"
            :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-form-item>
    </el-form>

    <el-table v-loading="loading" :data="tableList" :max-height="650">
      <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" />
      <el-table-column label="结算单位" align="center" prop="unitName" width="200" />
      <el-table-column label="结算工程" align="center" prop="projectName" width="200" />
      <el-table-column label="合计费用（元）" align="center" prop="costs" :show-overflow-tooltip="true">
        <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="auditor" :show-overflow-tooltip="true" />
      <el-table-column label="审批时间" align="center" prop="auditTime" width="100" />
      <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" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="normal" icon="el-icon-search" @click="handleView(scope.row)">查看</el-button>
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="handleExame(scope.row)"
            v-if="scope.row.sltStatus == '1'"
          >
            审批
          </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 title="结算审批" :visible.sync="applyVisible" width="650px" append-to-body>
      <el-form ref="aform" :model="aform" label-width="120px">
        <el-form-item label="结算审批" prop="status">
          <el-radio v-model="aform.status" label="2">通过</el-radio>
          <el-radio v-model="aform.status" label="3">不通过</el-radio>
        </el-form-item>
        <el-form-item label="原因" prop="remark">
          <el-input
            v-model="aform.remark"
            maxlength="100"
            placeholder="请输入"
            show-word-limit
            size="small"
            style="width: 350px"
            type="textarea"
            rows="4"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="primary" @click="submitListForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 协议单弹窗 -->
    <el-dialog :visible.sync="openPrint" width="1100px" append-to-body>
      <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 }}</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>

                 <img 
                  :src="agreementContent.auditorSignUrl" 
                  style="width: 40px; height: 90px; max-width: 100%; vertical-align: middle;" 
                  :style="{ transform: agreementContent.signType == 0 ? 'rotate(-90deg)' : '' }" 
                  alt="" 
                />

              </div>
            </div>

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

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

                
                   <img
                                    :src="agreementContent.sltSignUrl"
                                    style="width: 40px; height: 90px; max-width: 100%"
                                   :style="{ transform: agreementContent.signType == 0 ? 'rotate(-90deg)' : '' }" 
                                    alt=""
                                />
              </div>
            </div>
          </div>
        </vue-easy-print>
      </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 { getProjectList, getUnitList, getAgreementInfoById } from '@/api/back/index.js'
import {getClzSltList, costExamine, getSltInfo, getClzSettledInfo, clzCostExamine} 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'
export default {
  name: 'CostApplyList',
  dicts: ['cost_status'],
  components: { Treeselect, vueEasyPrint },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 单位数据
      unitList: [],
      // 工程数据
      proList: [],
      unitIds: null,
      projectIds: null,
      selectTreeProps: {
        children: 'children',
        label: 'name',
        value: 'id'
        // multiple: true,//false
      },
      // 表格数据
      tableList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyWord: undefined,
        sltStatus: '',
        isCommit: '',
        unitId: null,
        projectId: null,
        agreementId: null,
        agreementCode: null
      },
      openPrint: false,
      // 审批弹窗
      aform: { status: '2' },
      //审批弹窗是否开启
      applyVisible: false,
      id: '',
      agreementIdTemp: '',
      // 协议书内容
      agreementContent: {
        agreementCode: '',
        projectName: '',
        unitName: '',
        leaseCost: '', // 租赁费用
        repairCost: '', // 维修费用
        loseCost: '', // 丢失费用
        scrapCost: '', // 报废费用
        reductionCost: '', // 减免费用
        costAll: '', // 合计费用
        costAllUpper: '' // 合计费用大写
      }
    }
  },
  created() {
    this.GetUnitData()
    this.GetProData()
    this.getList()
  },
  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 params = {
        // projectId: this.queryParams.projectId /*  */,
      }
      const res = await getUnitList(params)
      this.unitList = res.data

      this.getAgreementInfo()
    },
    unitChange(val) {
      setTimeout(() => {
        this.queryParams.projectId = null
        this.queryParams.agreementId = null
        this.queryParams.agreementCode = null
        this.GetProData()
      }, 500)
    },
    // 获取 工程名称 列表数据
    async GetProData() {
      const params = {
        unitId: this.queryParams.unitId
      }
      const res = await getProjectList(params)
      this.proList = res.data

      this.getAgreementInfo()
    },
    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
        }
        const res = await getAgreementInfoById(params)
        console.log(res)
        if (!(res.data && res.data.agreementId)) {
          this.$message.error('当前单位和工程无协议！')
          this.queryParams.unitId = null
          this.queryParams.projectId = null
          this.GetUnitData()
          this.GetProData()
        } else {
          this.queryParams.agreementId = res.data.agreementId
          this.queryParams.agreementCode = res.data.agreementCode
        }
      }
    },

    /** 查询列表 */
    getList() {
      this.loading = true
      getClzSltList(this.queryParams).then(response => {
        this.tableList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        sltStatus: '',
        isCommit: '',
        unitId: null,
        projectId: null,
        agreementId: '',
        agreementCode: ''
      }
      this.resetForm('queryForm')
      this.handleQuery()
    },
    //结算审批查看
    handleView(row) {
      let arr = []
      arr.push(row)
      this.$emit('goDetail', JSON.stringify(arr))
    },
    //结算审批
    handleExame(row) {
      console.log(row)
      this.sltApplyCode = row.sltApplyCode
      this.id = row.id
      this.agreementIdTemp = row.agreementId
      this.applyVisible = true
    },
    //提交按钮
    submitListForm() {
      let param = {
        id: this.id,
        status: this.aform.status,
        remark: this.aform.remark,
        agreementId: this.agreementIdTemp,
        code: this.sltApplyCode,
      }
      clzCostExamine(param)
        .then(res => {
          if (res.code == 200) {
            this.$modal.msgSuccess('审批成功')
            this.getList()
            this.applyVisible = false
          } else {
            this.$modal.msgError(res.msg)
          }
        })
        .catch(() => {})
    },

    //取消按钮
    cancel() {
      this.applyVisible = false
      this.aform = { status: '2' }
    },

    async openPrintDialog(row) {
      this.openPrint = true
      try {
        const res = await getSltInfo([row])
        console.log('🚀 ~ openPrintDialog ~ res:', res)
        if (!res.data) return
        this.agreementContent = res.data
        this.agreementContent.agreementCode = row.agreementCode
        this.agreementContent.costAll =
          Number(res.data.leaseCost) +
          Number(res.data.repairCost) +
          Number(res.data.scrapCost) +
          Number(res.data.loseCost) -
          Number(res.data.reductionCost)
        // costAllUpper 中文大写
        this.agreementContent.costAllUpper = toChineseAmount(this.agreementContent.costAll.toFixed(2))
      } catch (error) {
        console.log('🚀 ~ openPrintDialog ~ error:', error)
      }
    },
    //维修任务单打印
    print() {
      this.$refs.remarksPrintRef.print()
    }
  }
}
</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>
