<template>
  <at-table
    @load="loadData"
    :data="data"
    :page-result="pageResult"
    ref="AtTable"
    :dialogTitle="dialogTitle"
    :dialogVisible="dialogVisible"
    @select-all="handleSelect"
    @select="handleSelect"
    @handleDialogCancel="handleDialogCancel"
    @handleDialogClose="handleDialogClose"
    @handleDialogSubmit="handleDialogSubmit"
    @row-dblclick="handleRowDBClick"
  >
    <template v-slot:searchInput>
      <el-form
        ref="searchForm"
        :model="searchForm"
        label-width="80px"
        class="search-top"
        @submit.native.prevent
      >
        <project-info-selector
          v-if="isShow"
          v-model="searchForm.projectId"
          style="width: 100%"
          @keyup.enter.native="findinfo"
        ></project-info-selector>
        <!-- <el-input
          v-model="searchForm.projectCode"
          style="width: 100%"
          clearable
          placeholder="请输入项目代码"
          @keyup.enter.native="findinfo"
        ></el-input> -->
        <el-input
          v-model="searchForm.filingAuthorityOpinions"
          placeholder="请输入结算单位"
          style="width: 100%"
          clearable
          @keyup.enter.native="findinfo"
        ></el-input>
        <el-date-picker
          v-model="searchForm.filingAuthorityDate"
          type="date"
          placeholder="请选择结算时间"
          value-format="yyyy-MM-dd"
          format="yyyy-MM-dd"
          clearable
          @keyup.enter.native="findinfo"
        >
        </el-date-picker>
        <!-- <el-input
          v-model="searchForm.constructUnit"
          placeholder="请输入施工单位"
          style="width: 100%"
          clearable
          @keyup.enter.native="findinfo"
        ></el-input> -->
        <el-button
          size="small"
          @click="findinfo"
          type="primary"
          class="el-icon-search search-btn"
          >查询</el-button
        >
        <el-button
          size="small"
          @click="handleReset"
          type="primary"
          plain
          class="el-icon-refresh"
          >重置</el-button
        >
      </el-form>
    </template>
    <template v-slot:operationBtn>
      <el-button
        size="small"
        type="primary"
        @click="handleAdd"
        icon="el-icon-plus"
        >添加</el-button
      >
      <ht-delete-button
        :url="deleteUrl"
        :requestMethod="'POST'"
        :htTable="$refs.AtTable"
        >删除</ht-delete-button
      >
      <import-file :importData="importData" @load="load"></import-file>
      <el-button
        size="small"
        type="primary"
        @click="handleExport"
        icon="el-icon-download"
        plain
        style="margin-left: 10px"
        >导出</el-button
      >
    </template>
    <template>
      <el-table-column type="selection" width="55" align="center">
      </el-table-column>
      <el-table-column type="index" label="序号" width="55" align="center">
      </el-table-column>
      <el-table-column
        prop="projectInfo.projectName"
        label="项目名称"
        :show-overflow-tooltip="true"
        align="center"
      >
      </el-table-column>
      <!-- <el-table-column
        prop="contractInfo.contractNumber"
        label="合同编号"
        :show-overflow-tooltip="true"
        align="center"
      >
      </el-table-column>
       <el-table-column
        prop="contractName"
        label="合同名称"
        :show-overflow-tooltip="true"
        align="center"
      >
      </el-table-column> -->
      <el-table-column
        prop="filingAuthorityDate"
        label="结算时间"
        :show-overflow-tooltip="true"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="filingAuthorityOpinions"
        label="结算单位"
        :show-overflow-tooltip="true"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="filingAuthoritySendDate"
        label="结算报送时间"
        :show-overflow-tooltip="true"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="filingAuthorityRegistrantSend"
        label="结算报送金额(元)"
        :show-overflow-tooltip="true"
        align="center"
      >
      </el-table-column>

      <el-table-column
        prop="firstInstancePrice"
        label="结算金额(元)"
        :show-overflow-tooltip="true"
        align="center"
      >
      </el-table-column>
      <!--  <el-table-column
        prop="handler"
        label="经办人"
        :show-overflow-tooltip="true"
        align="center"
      >
      </el-table-column>
       <el-table-column
        prop="approvalOpinion"
        label="备案机关审批意见"
        :show-overflow-tooltip="true"
        min-width="110"
        align="center"
      >
      </el-table-column> -->
      <el-table-column
        prop="remarks"
        label="备注"
        width="120"
        :show-overflow-tooltip="true"
        align="center"
      >
      </el-table-column>
    </template>
    <template v-slot:dialogContent>
      <el-form
        ref="form"
        v-form
        data-vv-scope="form"
        :model="form"
        :rules="rules"
        label-width="180px"
        v-if="dialogVisible"
        v-loading.fullscreen="loading"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectInfo.projectName">
              <el-input
                v-model="form.projectInfo.projectName"
                placeholder="请选择项目名称"
                @focus="handleFocusProject"
                :disabled="!isShow"
                clearable
              >
                <el-button
                  type="primary"
                  @click="openProject"
                  slot="append"
                  icon="el-icon-search"
                ></el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同名称" prop="contractInfo.name">
              <el-input
                v-model="form.contractInfo.name"
                placeholder="请选择所属合同"
                @focus="handleFocusContractName"
                clearable
              >
                <el-button
                  type="primary"
                  @click="handleFocusContractName"
                  slot="append"
                  icon="el-icon-search"
                ></el-button>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- <el-row>
          <el-col :span="12">
            
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同编号" prop="contractInfo.contractNumber">
              <el-input
                v-model="form.contractInfo.contractNumber"
                placeholder="请输入合同编号"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row> -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="结算单位" prop="filingAuthorityOpinions">
              <el-input
                v-model="form.filingAuthorityOpinions"
                placeholder="请输入结算单位"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经办人" prop="handler">
              <el-input
                v-model="form.handler"
                placeholder="请输入经办人"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="结算报送时间" prop="filingAuthoritySendDate">
              <el-date-picker
                v-model="form.filingAuthoritySendDate"
                type="date"
                placeholder="选择结算报送时间"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
                style="width: 100%"
                clearable
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="结算报送金额"
              prop="filingAuthorityRegistrantSend"
            >
              <el-input
                v-model="form.filingAuthorityRegistrantSend"
                placeholder="请输入结算报送金额"
                clearable
                type="number"
              >
                <i slot="suffix">元</i>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="结算时间" prop="filingAuthorityDate">
              <!-- <el-input
                v-model="form.filingAuthorityDate"
                placeholder="请输入结算时间"
                clearable
              ></el-input> -->
              <el-date-picker
                v-model="form.filingAuthorityDate"
                type="date"
                placeholder="选择结算时间"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
                style="width: 100%"
                clearable
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结算一审金额" prop="firstInstancePrice">
              <el-input
                v-model="form.firstInstancePrice"
                placeholder="请输入结算一审金额"
                clearable
                type="number"
              >
                <i slot="suffix">元</i>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <!-- <el-col :span="12">
            <el-form-item
              label="工程结算一审审核金额"
              prop="firstInstancePrice"
            >
              <el-input
                v-model="form.firstInstancePrice"
                placeholder="请输入工程结算一审审核金额"
              >
                <i slot="suffix">元</i>
              </el-input>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="结算二审金额" prop="secondInstancePrice">
              <el-input
                v-model="form.secondInstancePrice"
                placeholder="请输入结算二审金额"
              >
                <i slot="suffix">元</i>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同金额" prop="contractInfo.contractAmount">
              <el-input
                v-model="form.contractInfo.contractAmount"
                placeholder="请输入合同金额"
              >
                <i slot="suffix">元</i>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="签订日期" prop="contractInfo.contractDate">
              <el-date-picker
                v-model="form.contractInfo.contractDate"
                type="date"
                placeholder="选择签订日期"
                value-format="yyyy-MM-dd"
                format="yyyy-MM-dd"
                style="width: 100%"
                disabled
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="甲方单位" prop="contractInfo.firstParty">
              <el-input
                v-model="form.contractInfo.firstParty"
                placeholder="请输入甲方单位"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="乙方单位" prop="contractInfo.secondParty">
              <el-input
                v-model="form.contractInfo.secondParty"
                placeholder="请输入乙方单位"
                disabled
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="审批意见" prop="approvalOpinion">
          <el-input
            type="textarea"
            v-model="form.approvalOpinion"
            placeholder="请输入审批意见"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="form.remarks"
            placeholder="请输入备注"
            type="textarea"
          ></el-input>
        </el-form-item>
        <file-table
          @handleFile="handleFile"
          :file="form.accessoryInfo"
          :info="'上传工程结算审批文件'"
        />
        <project-info-dialog
          ref="project"
          :single="true"
          @select="handleSelectProject"
        ></project-info-dialog>
        <contract-info-dialog
          ref="contract"
          :single="true"
          @handleContract="handleContract"
        >
        </contract-info-dialog>
      </el-form>
    </template>
  </at-table>
</template>

<script>
import date from '@/api/date.js'
import req from '@/request.js'
import ProjectInfoDialog from '@/components/dialog/ProjectInfoDialog.vue'
import ContractInfoDialog from '@/components/dialog/ContractInfoDialog.vue'
const eipUserSelector = () =>
  import('@/components/selector/EipUserSelector.vue')
export default {
  name: 'Settlement',
  components: {
    ProjectInfoDialog,
    eipUserSelector,
    ContractInfoDialog,
  },
  props: {
    pid: {
      type: String,
      default: '',
    },
    isShow: {
      type: Boolean,
      default: true,
    },
  },
  data() {
    return {
      importData: {
        title: '结算导入',
        templateName: '结算模板.xls',
        downloadUrl: '/../fvue/static/excel/settlement.xlsx',
        importUrl:
          window.context.cqxy +
          '/biz/completionAcceptance/acceptanceSettlement/v1/importExcelData',
        showProject: true,
        showContract: true,
        projectId: '',
        contractName: '',
        //  params:{
        //     contractId: '',
        //   contractName: '',
        //  }
      },
      projectObj: [],
      loading: false,
      searchForm: {
        projectId: '',
        // projectCode: '',
        filingAuthorityDate: '',
        filingAuthorityOpinions: '',
      }, //顶部搜索参数
      data: [], //表格数据
      pageResult: {
        page: 1,
        pageSize: 20,
        total: 0,
      },
      form: {},
      dialogVisible: false,
      dialogTitle: '添加',
      indexArr: [],
      rules: {
        'projectInfo.projectName': {
          required: true,
          message: '请选择项目名称',
          trigger: 'blur',
        },
        'projectInfo.projectCode': {
          required: true,
          message: '请选择项目代码',
          trigger: 'blur',
        },
        'contractInfo.name': {
          required: true,
          message: '请选择所属合同',
          trigger: 'blur',
        },
        'contractInfo.contractNumber': {
          required: true,
          message: '请选择所属合同编号',
          trigger: 'blur',
        },
        filingAuthorityOpinions: {
          required: true,
          message: '请输入结算单位',
          trigger: 'blur',
        },
        filingAuthorityDate: {
          required: true,
          message: '请输入结算时间',
          trigger: 'blur',
        },
        firstInstancePrice: {
          required: true,
          message: '请输入结算一审金额',
          trigger: 'blur',
        },
        handler: {
          required: true,
          message: '请输入经办人',
          trigger: 'blur',
        },
        filingAuthoritySendDate: {
          required: true,
          message: '请选择结算报送时间',
          trigger: 'blur',
        },
        filingAuthorityRegistrantSend: {
          required: true,
          message: '请输入结算报送金额',
          trigger: 'blur',
        },
      },
    }
  },
  computed: {
    deleteUrl: function () {
      return (
        window.context.cqxy +
        '/biz/completionAcceptance/acceptanceSettlement/v1/delete'
      )
    },
  },
  mounted() {
    this.initProjectAll()
  },
  methods: {
    handleReset() {
      this.searchForm.projectId = ''
      this.searchForm.projectCode = ''
      this.searchForm.filingAuthorityOpinions = ''
      this.searchForm.filingAuthorityDate = ''
      this.searchForm.constructUnit = ''
      this.$refs['searchForm'].resetFields()
      this.pageResult = {
        page: 1,
        pageSize: 20,
        total: 0,
      }
      this.$refs['searchForm'].resetFields()
      this.$nextTick(() => {
        this.$refs.AtTable.load()
      })
    },
    //合同数据获取
    handleFocusContractName() {
      this.$refs.contract.open(this.form.projectId)
    },
    handleContract(data) {
      this.form.contractId = data.id
      this.form.contractName = data.name
      this.form.filingAuthorityOpinions = data.secondParty
      this.form.contractInfo = {...data}
      this.$refs.form.clearValidate()
    },
    handleDict(val, obj, str) {
      if (str === 'htgl-zbfs') {
        this.form.biddingChargeTypeValue = obj.name
      } else if (str === 'htgl-htlb') {
        this.form.contractInfo.typeValue = obj.name
      }
    },
    //导入后重新加载数据
    load() {
      this.$refs.AtTable.load()
    },
    //导出
    handleExport() {
      let query = []
      let search = {
        'pm.ID_': this.searchForm.projectId,
        // project_code_: this.searchForm.projectCode,
        filing_authority_opinions_: this.searchForm.filingAuthorityOpinions,
        filing_authority_date_: this.searchForm.filingAuthorityDate,
        // construct_unit_: this.searchForm.constructUnit,
      }
      if (!this.isShow) {
        search['pm.ID_'] = this.pid
      }
      for (let i in search) {
        if (search[i]) {
          query.push({
            group: 'advance',
            operation: 'LIKE',
            property: i,
            relation: 'AND',
            value: search[i],
          })
        }
      }
      let data = {
        pageBean: {
          page: 1,
          pageSize: 20,
          showTotal: true,
        },
        querys: query,
      }
      req
        .downloadPostCopy(
          '${cqxy}/biz/completionAcceptance/acceptanceSettlement/v1/exportDataToExcel',
          data
        )
        .then((res) => {
          if (res.status === 200) {
            this.$message.success('导出成功')
          } else {
            this.$message.error('导出失败')
          }
        })
    },
    handleFile(file) {
      this.form.accessoryInfo = file
    },
    handleAdd() {
      this.dialogTitle = '添加'
      this.form = {
        filingAuthorityDate: '',
        projectId: '',
        handler: '',
        projectInfo: {
          projectName: '',
          projectCode: '',
        },
        accessoryInfo: [],
        contractInfo: {
          name: '',
          contractNumber: '',
        },
        firstInstancePrice: '',
        secondInstancePrice: '',
        filingAuthoritySendDate: date.getDate(),
      }
      this.form.filingAuthorityDate = date.getDate()
      this.dialogVisible = true
      if (this.isShow) {
        let selectedProject = this.projectObj.find((item) => {
          if (item.currentProject && item.currentProject == 1) {
            return item.currentProject == 1
          }
        })
        this.form.projectInfo.projectName = selectedProject.projectName
        this.form.projectInfo.projectCode = selectedProject.projectCode
        this.form.projectId = selectedProject.id
        this.form.handler = selectedProject.projectManager
      } else {
        //根据项目id查询
        this.form.projectInfo.projectName = this.projectObj[0].projectName
        this.form.projectInfo.projectCode = this.projectObj[0].projectCode
        this.form.projectId = this.projectObj[0].id
        this.form.handler = this.projectObj[0].projectManager
      }
    },
    handleRowDBClick(data) {
      this.dialogTitle = '修改'
      this.form = data
      this.dialogVisible = true
    },
    handleFocusProject() {
      this.$refs.project.open()
    },
    openProject() {
      this.$refs.project.open()
    },
    handleSelectProject(data) {
      this.form.projectId = data.id
      this.form.projectInfo.projectCode = data.projectCode
      this.form.projectInfo.projectName = data.projectName
      this.form.handler = data.projectManager
      // this.form.projectInfo = {...data}
      this.form.contractInfo.name = ''
      this.form.contractInfo.contractNumber = ''
      this.form.contractInfo.projectId = data.id

      this.$refs.form.clearValidate()
    },
    handleSelect(selection) {},
    handleDialogCancel() {
      this.dialogVisible = false
      this.form = {
        projectInfo: {},
        accessoryInfo: [],
        contractInfo: {},
      }
    },
    handleDialogClose() {
      this.form = {
        projectInfo: {},
        accessoryInfo: [],
        contractInfo: {},
      }
      this.dialogVisible = false
    },
    initProjectAll() {
      //初始获取所有项目数据
      if (this.isShow) {
        this.$http.post('${cqxy}/biz/projectManagement/pm/v1/All').then(
          (res) => {
            this.projectObj = res.data.value
          },
          (error) => {
            reject(error)
          }
        )
      } else {
        let params = {
          pageBean: {
            page: 1,
            pageSize: 500,
            total: 0,
          },
          querys: [
            {
              group: 'main',
              operation: 'EQUAL',
              property: 'id',
              relation: 'AND',
              value: this.pid,
            },
          ],
        }
        this.$http
          .post('${cqxy}/biz/projectManagement/pm/v1/page', params)
          .then((res) => {
            if (res.data.state) {
              let resp = res.data.value
              this.projectObj = resp.rows
            }
          })
      }
    },
    //提交保存
    handleDialogSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.accessoryInfo && this.form.accessoryInfo.length > 0) {
            this.form.accessoryInfo.forEach((item) => {
              if (item.id) {
                delete item.id
              }
            })
          }
          this.loading = true
          this.$http
            .post(
              '${cqxy}/biz/completionAcceptance/acceptanceSettlement/v1/save',
              this.form
            )
            .then((res) => {
              if (res.data.state) {
                this.$refs.form.resetFields()
                this.$message.success(res.data.message)
                this.dialogVisible = false
                this.$refs.AtTable.load()
              } else {
                this.$message.error(res.data.message)
              }
              this.loading = false
            })
        }
        // else if (this.form.accessoryInfo.length === 0) {
        //   this.$message.error('请至少上传一个附件')
        // }
        else {
          this.$message({
            message: '*号必填项,不能为空!',
            type: 'warning',
          })
          return false
        }
      })
    },
    loadData(param, cb) {
      let query = []
      let search = {
        'pm.id_': this.searchForm.projectId,
        // project_code_: this.searchForm.projectCode,
        filing_authority_opinions_: this.searchForm.filingAuthorityOpinions,
        filing_authority_date_: this.searchForm.filingAuthorityDate,
      }
      if (!this.isShow) {
        search['pm.ID_'] = this.pid
        this.importData.projectId = this.pid
      }
      for (let i in search) {
        if (search[i]) {
          query.push({
            group: 'advance',
            operation: 'LIKE',
            property: i,
            relation: 'AND',
            value: search[i],
          })
        }
      }
      if (param.querys && param.querys.length) {
        param.querys.push(...query)
      } else {
        param.querys = query
      }
      this.$http
        .post(
          '${cqxy}/biz/completionAcceptance/acceptanceSettlement/v1/page',
          param
        )
        .then(
          (resp) => {
            let response = resp.data.value
            this.data = response.rows
            this.pageResult = {
              page: response.page,
              pageSize: response.pageSize,
              total: response.total,
            }
          },
          (error) => {
            reject(error)
          }
        )
        .finally(() => {
          if (cb) {
            cb()
          }
        })
    },
    findinfo() {
      this.$refs.AtTable.load()
    },
  },
}
</script>
<style lang="scss" scoped>
@import '@/assets/css/common.scss';
/deep/ .el-range-editor--small .el-range-separator {
  display: contents;
}
</style>
