<template>
  <div class="cooperative-group-container">
    <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="combineName" slot-scope="scope">
        <span v-if="scope.row.combineName" @click="viewEnterprise(scope.row)"
          v-html="scope.row.combineName">{{scope.row.combineName}}</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">

      <!-- tab切换栏 -->
      <dsk-tab-toggle v-model="currentList" :tabs="toggleTabs" @tabToggle="tabToggle"></dsk-tab-toggle>

      <div class="cooperation-record-dialog-innner">

        <!-- 成员列表 -->
        <template v-if="currentList == 'cooperativeMember'">
          <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="memberForData"
            :tableDataTotal="dialogtableDataTotal" :queryParams="dialogQueryParams" @handle-current-change="dialogCurrentChange"
            @sort-change="dialogSortChange" :maxHeight="true">
            <!-- 合作成员-->
            <template slot="companyName" slot-scope="scope">
              <span v-if="scope.row.companyName" style="color: #0081FF;cursor: pointer;"
                v-html="scope.row.companyName">{{scope.row.companyName}}</span>
              <span v-else>-</span>
            </template>
            <!-- 合作项目数量 -->
            <template slot="count" slot-scope="scope">
              <span v-if="scope.row.count" style="color: #0081FF;cursor: pointer;">{{scope.row.count}}</span>
              <span v-else>-</span>
            </template>
          </dialog-tables>
        </template>

        <!-- 项目列表 -->
        <template v-if="currentList == 'cooperativeProject'">
          <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>
                <span @click="linkTo1(scope.row.sourceId)" v-if="scope.row.projectName" style="color: #0081FF;cursor: pointer;" 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="companyName" slot-scope="scope">
              <span v-if="scope.row.companyName" style="color: #0081FF;cursor: pointer;"
                v-html="scope.row.companyName">{{scope.row.companyName}}</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>
        </template>

      </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, getCooperativeGroupMemberApi } from "@/api/consultingTransaction";
import DialogHeadFormNew from "../component/HeadFormNew";
import DialogTables from "../component/Tables";
import DskTabToggle from "@/components/DskTabToggle";
import { replaceDomTags } from "@/utils";
import { encodeStr } from "@/assets/js/common";
import {skyProjectDetail} from '@/api/detail/party-a/dealings'
export default {
  name: "cooperativeGroup",
  mixins: [mixin],
  components: {
    skeleton,
    DialogHeadFormNew,
    DialogTables,
    DskTabToggle
  },
  props: ['companyId'],
  data() {
    return {
      currentList: "cooperativeMember",
      toggleTabs: [
        {
          value: "cooperativeMember",
          name: "成员列表",
          id: this.getUid()
        },
        {
          value: "cooperativeProject",
          name: "项目列表",
          id: this.getUid()
        }
      ],
      queryParams: {
        companyId: this.companyId,
        pageNum: 1,
        pageSize: 10,
        companyType: 3,
        sort: ""
      },
      selectOptions: {},
      forData: [
        { label: '集团名称', prop: 'combineName', 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', 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,
        memberName: "",
        combineName: "",
        pageNum: 1,
        pageSize: 10,
        companyType: 3,
        sort: ""
      },
      memberForData: [
        { label: '合作成员', prop: 'companyName', width: '351', slot: true, showOverflowTooltip: true },
        { label: '合作次数', prop: 'count', minWidth: '223', align: "right", slot: true, sortable: "custom" },
        { label: '最近一次合作时间', prop: 'time', minWidth: '214', sortable: "custom" },
        // { label: '合作总金额（万元）', prop: 'amount', minWidth: '226', align: "right", sortable: "custom" },
      ],
      dialogForData: [
        { label: '合作项目/工程名称', prop: 'projectName', width: '350', slot: true, showOverflowTooltip: true },
        { label: '合作成员', prop: 'companyName', width: '350', slot: true, showOverflowTooltip: true },
        { label: '合作时间', prop: 'time', width: '140', sortable: "custom" },
        { label: '集团成员身份', prop: 'role', width: '140' },
        { label: '咨询机构承担角色', prop: 'agencyBusinessType', width: '140' },
        { label: '项目类型', prop: 'counterpartRole', minWidth: '105' },
        { label: '工程类型', prop: 'projectType', minWidth: '100' },
        { label: '项目/工程金额（万元）', slot: true, prop: 'amount', width: '190', sortable: "custom", align: "right", },
        { label: '项目地区', prop: 'area', width: '245', slot: true },
      ],
      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: [],
      selectDialogOptions: {},
      statisticsData: {},
    };
  },
  //可访问data属性
  created() {
    this.initDetail();
  },
  //计算集
  computed: {

  },
  //方法集
  methods: {
    async initDetail() {
      try {
        await this.setOptions();
        await this.setDialogOptions();
        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]) => {
            const _temp = this.formData.find(formItem => value == formItem.fieldName);
            if (_temp) {
              this.$set(_temp, "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.$router.push(`/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.memberName = row.combineName;
      this.dialogQueryParams.combineName = row.combineName;
      this.cooperationRecordDialog = true;
    },
    async dialogHandleQurey(params) {
      try {
        let data = params ? params : this.dialogQueryParams;
        const _tempData = JSON.parse(JSON.stringify(data));
        this.currentList == "cooperativeMember" ? delete _tempData.memberName : delete _tempData.memberName;
        this.dialogIsSkeleton = true;
        const res = this.currentList == "cooperativeMember" ? await getCooperativeGroupMemberApi(_tempData) : await getCooperativeOwnerUnitsDetailApi(_tempData);
        this.dialogTableData = res.rows ? res.rows : [];
        this.dialogtableDataTotal = res.total ? res.total : 0;
        const dialogData = JSON.parse(JSON.stringify(data));
        delete dialogData.memberName;
        const count = await getCooperativeOwnerUnitsCountAmountApi(dialogData);
        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 }));
        this.currentList == "cooperativeMember" ? delete searchParams.memberName : delete searchParams.memberName;
        const res = this.currentList == "cooperativeMember" ? await getCooperativeGroupMemberApi(searchParams) : await getCooperativeOwnerUnitsDetailApi(searchParams);
        this.dialogTableData = res.rows ? res.rows : [];
        this.dialogtableDataTotal = res.total ? res.total : 0;
        const dialogData = JSON.parse(JSON.stringify(this.dialogQueryParams));
        delete dialogData.memberName;
        const count = await getCooperativeOwnerUnitsCountAmountApi(dialogData);
        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;
    },
    async resetDialogQuery() {
      try {
        const data = this.$options.data.call(this);
        this.dialogTableData = data.dialogTableData;
        this.statisticsData = data.statisticsData;
        this.dialogtableDataTotal = data.dialogtableDataTotal;
        this.dialogFormData = data.dialogFormData;
        this.dialogQueryParams.pageNum = 1;
        this.dialogQueryParams.pageSize = 10;
        await this.setDialogOptions();
      } catch (error) {
        console.log(error);
      }
    },
    // 切换tab
    async tabToggle() {
      await this.resetDialogQuery();
      await this.dialogHandleQurey();
    },
    linkTo1(id){
      let url = ""
      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-group-container {
  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: 0px;

        .cooperation-record-dialog-innner {
          width: 100%;
          height: calc(100% - 48px);
          padding: 24px 20px;
          box-sizing: border-box;

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

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