<template>
  <div class="cooperative-construction-unit">
    <head-form-new title="常合作施工单位" :form-data="formData" :query-params="queryParams" :total="tableDataTotal" :isExcel="true"
      @handle-search="handleSearch" />
    <skeleton v-if="isSkeleton" style="padding: 16px"></skeleton>
    <tables v-if="!isSkeleton" :indexFixed="true" :tableData="tableData" :forData="forData" :tableDataTotal="tableDataTotal"
      :queryParams="queryParams" @handle-current-change="handleCurrentChange" @sort-change="sortChange">
      <!-- 业主名称 -->
      <template slot="counterpartCompanyName" slot-scope="scope">
        <span v-if="scope.row.counterpartCompanyName" style="color: #0081FF;cursor: pointer;" @click="viewEnterprise(scope.row)"
          v-html="scope.row.counterpartCompanyName">{{scope.row.counterpartCompanyName}}</span>
        <span v-else>-</span>
      </template>
      <!-- 合作总金额-->
      <template slot="amount" slot-scope="scope">
        <span v-if="scope.row.amount">{{scope.row.amount.toFixed(2)}}</span>
        <span v-else>-</span>
      </template>
      <!-- 合作项目数量 -->
      <template slot="count" slot-scope="scope">
        <span v-if="scope.row.count" style="color: #0081FF;cursor: pointer;" @click="viewProject(scope.row)">{{scope.row.count}}</span>
        <span v-else>-</span>
      </template>
    </tables>

    <el-dialog title="合作项目/工程明细" :visible.sync="cooperationRecordDialog" width="1100px" @close="dialogClose" @open="dialogOPen" :modal-append-to-body="false"
      class="cooperation-record-dialog-container" custom-class="cooperation-record-dialog" :destroy-on-close="true" :close-on-click-modal="false">
      <div class="cooperation-record-dialog-innner">
        <dialog-head-form-new title="" :form-data="dialogFormData" :query-params="dialogQueryParams" :total="dialogtableDataTotal" :isExcel="false"
          @handle-search="dialogHandleSearch" ref="dialogSearchFormNew" />

        <skeleton v-if="dialogIsSkeleton" style="padding: 16px"></skeleton>

        <!-- 列表 -->
        <dialog-tables v-if="!dialogIsSkeleton" :indexFixed="true" :tableData="dialogTableData" :forData="dialogForData"
          :tableDataTotal="dialogtableDataTotal" :queryParams="dialogQueryParams" @handle-current-change="dialogCurrentChange"
          @sort-change="dialogSortChange" :maxHeight="true">
          <!-- 合作项目/工程名称-->
          <template slot="projectName" slot-scope="scope">
            <template v-if="scope.row.dataSource ==='中标业绩'">
              <router-link :to="`/biddetail/${scope.row.sourceId}`" tag="a" class="a-link" v-if="scope.row.sourceId" v-html="scope.row.projectName"></router-link>
              <div v-else v-html="scope.row.projectName || '--'"></div>
            </template>
            <template v-else>
              <span @click="linkTo1(scope.row.sourceId)" v-if="scope.row.projectName && scope.row.sourceId" style="color: #0081FF;cursor: pointer;" v-html="scope.row.projectName">{{scope.row.projectName}}</span>
              <span v-else-if="scope.row.projectName" v-html="scope.row.projectName">{{scope.row.projectName}}</span>
              <span v-else>-</span>
            </template>
          </template>
          <!-- 合作总金额-->
          <template slot="amount" slot-scope="scope">
            <span v-if="scope.row.amount">{{scope.row.amount.toFixed(2)}}</span>
            <span v-else>-</span>
          </template>
          <!-- 省市区 -->
          <template slot="area" slot-scope="scope">
            <span>{{`${scope.row.province ? scope.row.province : ""}${scope.row.province && scope.row.city ? " - " : ""}${scope.row.city ? scope.row.city : ""}${scope.row.city && scope.row.area ? " - " : ""}${scope.row.area ? scope.row.area : ""}`}}</span>
          </template>
        </dialog-tables>

      </div>
    </el-dialog>
  </div>
</template>
<script>
import skeleton from '../component/skeleton';
import mixin from '@/views/detail/party-a/mixins/mixin';
import { getCooperativeOwnerUnitsListApi, getCooperativeOwnerUnitsDetailApi, getCooperativeOwnerUnitsOptionsApi, getCooperativeOwnerUnitsCountAmountApi } from "@/api/consultingTransaction";
import DialogHeadFormNew from "../component/HeadFormNew";
import DialogTables from "../component/Tables";
import { replaceDomTags } from "@/utils";
import { encodeStr } from "@/assets/js/common";
import {skyProjectDetail} from '@/api/detail/party-a/dealings'
export default {
  name: "cooperativeConstructionUnit",
  mixins: [mixin],
  components: {
    skeleton,
    DialogHeadFormNew,
    DialogTables
  },
  props: ['companyId'],
  data() {
    return {
      queryParams: {
        companyId: this.companyId,
        pageNum: 1,
        pageSize: 10,
        companyType: 2,
        sort: ""
      },
      selectOptions: {},
      forData: [
        { label: '施工单位名称', prop: 'counterpartCompanyName', width: '295', slot: true, showOverflowTooltip: true },
        { label: '合作项目数量', prop: 'count', minWidth: '190', align: "right", slot: true, sortable: "custom" },
        { label: '最近一次合作时间', prop: 'time', minWidth: '214', sortable: "custom" },
        { label: '合作总金额（万元）', prop: 'amount', slot: true, minWidth: '226', align: "right", sortable: "custom" },
      ],
      formData: [
        { type: 4, fieldName: 'businessTypes', value: '', placeholder: '咨询机构业务', options: [], uid: this.getUid() },
        { type: 4, fieldName: 'counterpartCompanyRoles', value: '', placeholder: '合作项目类型', options: [], uid: this.getUid() },
        { type: 4, fieldName: 'projectTypes', value: '', placeholder: '合作工程类型', options: [], uid: this.getUid() },
        { type: 5, fieldName: 'time', value: '', placeholder: '合作频率', startTime: 'beginTime', endTime: 'endTime', uid: this.getUid() },
        { type: 6, fieldName: 'money', value: '', placeholder: '合作金额', uid: this.getUid() },
        { type: 3, fieldName: 'keyword', value: '', placeholder: '请输入', uid: this.getUid() },
      ],
      //列表
      tableLoading: false,
      tableData: [],
      tableDataTotal: 0,
      isSkeleton: true,
      // 合作项目详情弹窗
      cooperationRecordDialog: false,
      dialogQueryParams: {
        companyId: this.companyId,
        combineName: "",
        pageNum: 1,
        pageSize: 10,
        companyType: 2,
        sort: ""
      },
      dialogForData: [
        { label: '合作项目/工程名称', prop: 'projectName', width: '260', slot: true, showOverflowTooltip: true },
        { label: '合作时间', prop: 'time', width: '140', sortable: "custom" },
        { label: '咨询机构承担角色', prop: 'agencyBusinessType', width: '140' },
        { label: '项目类型', prop: 'counterpartRole', minWidth: '105' },
        { label: '工程类型', prop: 'projectType', minWidth: '100' },
        { label: '项目/工程金额（万元）', prop: 'amount', slot: true, width: '190', sortable: "custom", align: "right", },
        { label: '项目地区', prop: 'area', width: '245', slot: true },
        { label: '数据来源', prop: 'dataSource', width: '90' },
      ],
      dialogFormData: [
        { type: 4, fieldName: 'businessTypes', value: '', placeholder: '咨询机构业务', options: [], uid: this.getUid() },
        { type: 4, fieldName: 'counterpartCompanyRoles', value: '', placeholder: '合作项目类型', options: [], uid: this.getUid() },
        { type: 4, fieldName: 'projectTypes', value: '', placeholder: '合作工程类型', options: [], uid: this.getUid() },
        { type: 5, fieldName: 'time', value: '', placeholder: '合作频率', startTime: 'beginTime', endTime: 'endTime', uid: this.getUid() },
        { type: 3, fieldName: 'keyword', value: '', placeholder: '请输入', uid: this.getUid() },
      ],
      dialogIsSkeleton: true,
      dialogtableDataTotal: 0,
      dialogTableData: [],
      statisticsData: {},
      selectDialogOptions: {}
    };
  },
  //可访问data属性
  created() {
    this.initDetail();
  },
  //计算集
  computed: {

  },
  //方法集
  methods: {
    async initDetail() {
      try {
        await this.setOptions();
        await this.handleQuery();
      } catch (error) {

      }
    },
    async setOptions() {
      try {
        const options = await getCooperativeOwnerUnitsOptionsApi({ companyId: this.queryParams.companyId });
        if (options.code == 200 && options.data) {
          for (const key in options.data) {
            options.data[key] = options.data[key].map(item => ({ name: item, value: item }));
          }
          this.selectOptions = options.data;
          const optionsKey = [["businessType", "businessTypes"], ["counterpartCompanyRole", "counterpartCompanyRoles"], ["projectType", "projectTypes"]];

          optionsKey.forEach(([key, value]) => {
            this.$set(this.formData.find(formItem => value == formItem.fieldName), "options", this.selectOptions[key]);
          });
        }
      } catch (error) {
        console.log(error);
      }
    },
    async setDialogOptions() {
      try {
        const options = await getCooperativeOwnerUnitsOptionsApi({ companyId: this.queryParams.companyId });
        if (options.code == 200 && options.data) {
          for (const key in options.data) {
            options.data[key] = options.data[key].map(item => ({ name: item, value: item }));
          }
          this.selectDialogOptions = options.data;
          const optionsKey = [["businessType", "businessTypes"], ["counterpartCompanyRole", "counterpartCompanyRoles"], ["projectType", "projectTypes"]];

          optionsKey.forEach(([key, value]) => {
            this.$set(this.dialogFormData.find(formItem => value == formItem.fieldName), "options", this.selectDialogOptions[key]);
          });
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 创建列表查询条件
    createQueryCondition(form) {
      /**
       * @type {Array<{
       * fieldName : string;
       * value : any
       * }>}
      */
      const paramsArray = JSON.parse(JSON.stringify(form));
      const params = {};
      // 处理查询参数
      paramsArray.forEach(item => {
        // 有效参数
        if ((item.value && item.value != "0" && !Array.isArray(item.value)) || item?.value?.length) {
          // 多选
          if (["businessTypes", "counterpartCompanyRoles", "projectTypes"].includes(item.fieldName)) {
            params[item.fieldName] = item.value;
          }
          // 时间处理
          if (item.fieldName == "time") {
            params["beginTime"] = item.value[0];
            params["endTime"] = item.value[1];
          }
          // 金额处理
          if (item.fieldName == "money") {
            params["minAmount"] = item.value[0] ? item.value[0] : "";
            params["maxAmount"] = item.value[1] ? item.value[1] : "";
          }
          // 搜索关键词处理
          if (item.fieldName == "keyword" && item?.value.trim()) {
            params["keyword"] = item.value;
          }
        }
      });
      return params;
    },
    // 查询
    async handleSearch() {
      const params = this.createQueryCondition(this.formData);
      this.queryParams.pageNum = 1;
      const searchParams = JSON.parse(JSON.stringify({ ...params, ...this.queryParams }));
      this.handleQuery(searchParams);
    },
    handleCurrentChange(page) {
      this.queryParams.pageNum = page;
      const params = this.createQueryCondition(this.formData);
      const searchParams = JSON.parse(JSON.stringify({ ...params, ...this.queryParams }));
      this.handleQuery(searchParams);
    },
    async handleQuery(params) {
      try {
        let data = params ? params : this.queryParams;
        this.isSkeleton = true;
        const res = await getCooperativeOwnerUnitsListApi(data);
        this.tableData = res.rows ? res.rows : [];
        this.tableDataTotal = res.total ? res.total : 0;
      } catch (error) {
        console.log(error);
      } finally {
        this.isSkeleton = false;
      }
    },
    viewEnterprise(row) {
      this.$tab.openPage(`${replaceDomTags(row.companyName)}详情`, `/enterprise/${encodeStr(row.companyId)}`, {
        companyName: replaceDomTags(row.companyName)
      });
    },
    async sortChange({ column, order, prop }) {
      let sort = null;
      switch (prop) {
        case "count":
          order == "ascending" ? sort = 6 : sort = 5;
          break;
        case "time":
          order == "ascending" ? sort = 4 : sort = 3;
          break;
        case "amount":
          order == "ascending" ? sort = 2 : sort = 1;
          break;
        default:
          break;
      }
      if (!order) sort = "";
      this.queryParams.sort = sort;
      try {
        const params = this.createQueryCondition(this.formData);
        const searchParams = JSON.parse(JSON.stringify({ ...params, ...this.queryParams }));
        const res = await getCooperativeOwnerUnitsListApi(searchParams);
        this.tableData = res.rows ? res.rows : [];
        this.tableDataTotal = res.total ? res.total : 0;
      } catch (error) {
        console.log(error);
      }
    },
    viewProject(row) {
      this.dialogQueryParams.combineName = row.counterpartCompanyName;
      this.cooperationRecordDialog = true;
    },
    async dialogHandleQurey(params) {
      try {
        let data = params ? params : this.dialogQueryParams;
        this.dialogIsSkeleton = true;
        const res = await getCooperativeOwnerUnitsDetailApi(data);
        this.dialogTableData = res.rows ? res.rows : [];
        this.dialogtableDataTotal = res.total ? res.total : 0;
        const count = await getCooperativeOwnerUnitsCountAmountApi(data);
        if (count.code == 200 && count.data) {
          this.statisticsData = count.data;
        }
      } catch (error) {
        console.log(error);
      } finally {
        this.dialogIsSkeleton = false;
      }
    },
    dialogHandleSearch(v) {
      const params = this.createQueryCondition(this.dialogFormData);
      this.dialogQueryParams.pageNum = 1;
      const searchParams = JSON.parse(JSON.stringify({ ...params, ...this.dialogQueryParams }));
      this.dialogHandleQurey(searchParams);
    },
    async dialogSortChange({ column, order, prop }) {
      let sort = null;
      switch (prop) {
        case "count":
          order == "ascending" ? sort = 6 : sort = 5;
          break;
        case "time":
          order == "ascending" ? sort = 4 : sort = 3;
          break;
        case "amount":
          order == "ascending" ? sort = 2 : sort = 1;
          break;
        default:
          break;
      }
      if (!order) sort = "";
      this.dialogQueryParams.sort = sort;
      try {
        const params = this.createQueryCondition(this.dialogFormData);
        const searchParams = JSON.parse(JSON.stringify({ ...params, ...this.dialogQueryParams }));
        const res = await getCooperativeOwnerUnitsDetailApi(searchParams);
        this.dialogTableData = res.rows ? res.rows : [];
        this.dialogtableDataTotal = res.total ? res.total : 0;
        const count = await getCooperativeOwnerUnitsCountAmountApi(JSON.parse(JSON.stringify(this.dialogQueryParams)));
        if (count.code == 200 && count.data) {
          this.statisticsData = count.data;
        }
      } catch (error) {
        console.log(error);
      }
    },
    dialogCurrentChange(page) {
      this.dialogQueryParams.pageNum = page;
      const params = this.createQueryCondition(this.dialogFormData);
      const searchParams = JSON.parse(JSON.stringify({ ...params, ...this.dialogQueryParams }));
      this.dialogHandleQurey(searchParams);
    },
    async dialogOPen() {
      await this.setDialogOptions();
      await this.dialogHandleQurey();
    },
    dialogClose() {
      const data = this.$options.data.call(this);
      this.dialogQueryParams = data.dialogQueryParams;
      this.dialogFormData = data.dialogFormData;
      this.dialogtableDataTotal = data.dialogtableDataTotal;
      this.dialogTableData = data.dialogTableData;
    },
    linkTo1(id){
      let url = ""
      if(id){
        skyProjectDetail({sourceId:id}).then(res=>{
          if(res.data&&res.data.sourceUrl){
            url = res.data.sourceUrl
            window.open(url, "_blank")
          }
        })
      }
    }
  },
}
</script>
<style lang="scss" scoped>
.cooperative-construction-unit {
  background: #ffffff;
  border-radius: 4px;
  padding: 16px;
  input {
    border: 1px solid #efefef;
  }
  ::v-deep .el-form-item {
    margin-right: 8px !important;
  }

  .query-box {
    margin: 10px 0 20px;
  }
  .cell-span {
    display: inline-block;
    position: relative;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 4;
    cursor: pointer;

    > span {
      display: inline-block;
      width: 37px;
      position: absolute;
      right: 0;
      bottom: 0;
      background-color: #fff;
      z-index: 1;
    }
  }
  @import "@/assets/styles/search-common.scss";

  ::v-deep .cooperation-record-dialog-container {
    .cooperation-record-dialog {
      height: 75%;
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      border-radius: 4px;
      margin: 0px !important;
      display: flex;
      flex-direction: column;

      .el-dialog__header {
        padding: 20px;
        height: 56px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        box-sizing: border-box;
        border-bottom: 1px solid #eeeeee;

        .el-dialog__title {
          color: #232323;
          font-weight: bold;
          line-height: 16px;
        }

        .el-dialog__headerbtn {
          position: static;
          width: 16px;
          height: 16px;
        }
      }

      .el-dialog__body {
        height: calc(100% - 56px);
        padding: 24px 20px;
        box-sizing: border-box;

        .cooperation-record-dialog-innner {
          width: 100%;
          height: 100%;

          .Tables {
            height: calc(100% - 40px);
          }
        }
      }

      .el-table-horizontal-scrollbar {
        display: none !important;
      }
    }
  }
}
</style>
