<template>
  <div id="wellInfoDetail">
    <a-layout>
      <a-layout-sider>
        <a-anchor wrapper-class="anchor" :target-offset="50"
                  @click.prevent="handleClickAnchor"
                  :get-container="getContainer">
          <a-anchor-link v-for="(item, index) in steps"
                         :href="item.id" :key="index" :title="item.title"/>
        </a-anchor>
      </a-layout-sider>
      <a-layout-content>
        <a-card id="jsjj" :bordered="false" :headStyle="cardSettings.cardHeadStyle" class="card-detail">
          <template #title>
            <div slot="title" style="width:100%" @click="cardSettings.cardSummary.expand=!cardSettings.cardSummary.expand">
              井史简介
            </div>
          </template>
          <template #extra>
            <UpSquareOutlined v-if="cardSettings.cardSummary.expand" @click="cardSettings.cardSummary.expand=false"
                              :style="cardSettings.buttonStyle"/>
            <DownSquareOutlined v-else @click="cardSettings.cardSummary.expand=true"
                                :style="cardSettings.buttonStyle"/>
          </template>
          <div v-if="cardSettings.cardSummary.expand" class="info-body" style="font-size: larger;">
            <p>
              井名<span>{{ dataModel.well_common_name }}</span>，
              井别<span>{{ dataModel.well_purpose }}</span>
            </p>
            <p>
              构造位置<span>{{dataModel.structure_pos}}</span>，
              <template v-if="dataModel.spud_date_fmt">
                于<span>{{ dataModel.spud_date_fmt }}</span>开钻
              </template>
              <template v-if="dataModel.end_drilling_date_fmt">
                ，<span>{{ dataModel.end_drilling_date_fmt }}</span>完钻
              </template>
              <template v-if="dataModel.completion_method">
                ，采取<span>{{ dataModel.completion_method }}</span>方式完井。
              </template>
            </p>

            <p>
              <template v-if="dataModel.prod_horizon">
                投产于<span>{{ dataModel.start_prod_date }}，</span>
              </template>
              <template v-if="dataModel.prod_horizon">
                生产层位<span>{{ dataModel.prod_horizon }}</span>层位。
              </template>
              <template v-if="dataModel.recent_testing_date">
                <span>{{ dataModel.recent_testing_date }}</span>
              </template>
              <template v-if="dataModel.recent_testing_name">
                进行最近一次<span>{{ dataModel.recent_testing_name }}</span>测试。
              </template>
              <template v-if="dataModel.recent_prod_date">
                最近一次产油时间<span>{{ dataModel.recent_prod_date }}</span>，
              </template>
              油嘴<span>{{ dataModel.oil_nozzle ?? '--' }}</span>mm
              ，油压<span>{{ dataModel.tubing_pres ?? '--' }}</span>MPa
              ，套压<span>{{ dataModel.casing_pres ?? '--' }}</span>MPa
              ，日产液量<span>{{ dataModel.fluid_prod_daily ?? '--' }}</span>t/d
              ，日产油量<span>{{ dataModel.oil_prod_daily ?? '--' }}</span>t/d
              ，含水<span>{{ dataModel.water_cut ?? '--' }}</span>%
              ，动液面<span>{{ dataModel.start_pump_liq_level ?? '--' }}</span>m
              ，截止目前累产油<span>{{ dataModel.oil_prod_cum ?? '--' }}</span>t。
            </p>
          </div>
        </a-card>
        <a-card id="scdt" :bordered="false" :headStyle="cardSettings.cardHeadStyle" class="card-detail">
          <template #title>
            <div slot="title" style="width:100%" @click="cardSettings.cardChat.expand=!cardSettings.cardChat.expand">生产动态
            </div>
          </template>
          <template #extra>
            <UpSquareOutlined v-if="cardSettings.cardChat.expand" @click="cardSettings.cardChat.expand=false"
                              :style="cardSettings.buttonStyle"/>
            <DownSquareOutlined v-else @click="cardSettings.cardChat.expand=true"
                                :style="cardSettings.buttonStyle"/>
          </template>
          <div v-if="cardSettings.cardChat.expand">
            <ChartProdDynmics :wellId="dataModel.well_id"></ChartProdDynmics>
          </div>
        </a-card>
        <a-card id="jbxx" :bordered="false" :headStyle="cardSettings.cardHeadStyle" class="card-detail">
          <template #title>
            <div slot="title" style="width:100%"
                 @click="cardSettings.cardBaseInfo.expand=!cardSettings.cardBaseInfo.expand">基本信息
            </div>
          </template>
          <template #extra>
            <UpSquareOutlined v-if="cardSettings.cardBaseInfo.expand" @click="cardSettings.cardBaseInfo.expand=false"
                              :style="cardSettings.buttonStyle"/>
            <DownSquareOutlined v-else @click="cardSettings.cardBaseInfo.expand=true"
                                :style="cardSettings.buttonStyle"/>
          </template>
          <div v-if="cardSettings.cardBaseInfo.expand" style="display: flex">
            <div style="width:70%">
              <a-divider type="vertical" class="info-title" style="margin-top: 0px" dashed>井身结构</a-divider>
              <a-descriptions bordered>
                <a-descriptions-item label="井名：" :labelStyle="{'width':'12%'}" :contentStyle="{'width':'21%'}">
                  {{ dataModel.well_common_name }}
                </a-descriptions-item>
                <a-descriptions-item style="color: well_purpose" label="井别：">{{ dataModel.well_purpose }}</a-descriptions-item>
                <a-descriptions-item label="井型：">{{ dataModel.well_type }}</a-descriptions-item>
                <a-descriptions-item label="开钻日期：">{{ dataModel.spud_date_fmt }}</a-descriptions-item>
                <a-descriptions-item label="完钻日期：">{{ dataModel.end_drilling_date_fmt }}</a-descriptions-item>
                <a-descriptions-item label="设计井深：">{{
                    dataModel.budgeted_md == null ? "" : (dataModel.budgeted_md + "m")
                  }}
                </a-descriptions-item>
                <a-descriptions-item label="完钻层位：">{{ dataModel.completion_formation }}</a-descriptions-item>
                <a-descriptions-item label="完井方式：">{{ dataModel.completion_method }}</a-descriptions-item>
                <a-descriptions-item label="生产井段：">{{ dataModel.well_production_sections }}</a-descriptions-item>
                <a-descriptions-item label="造斜点：">{{
                    dataModel.ko_azimuth == null ? "" : (dataModel.ko_azimuth + "m")
                  }}
                </a-descriptions-item>
                <a-descriptions-item label="水平位移：">
                  {{ dataModel.ko_horizontal_dislocation == null ? "" : (dataModel.ko_horizontal_dislocation + "m") }}
                </a-descriptions-item>
                <a-descriptions-item label="方位角：">{{
                    dataModel.azimuth_angle == null ? "" : (dataModel.azimuth_angle + "°")
                  }}
                </a-descriptions-item>
                <a-descriptions-item label="井位坐标经度：">{{ dataModel.well_coordinates_x }}</a-descriptions-item>
                <a-descriptions-item label="井位坐标纬度：">{{ dataModel.well_coordinates_y }}</a-descriptions-item>
                <a-descriptions-item label="x轴">{{ dataModel.geo_offset_east }}</a-descriptions-item>
                <a-descriptions-item label="y轴">{{ dataModel.geo_offset_nonth }}</a-descriptions-item>
              </a-descriptions>
              <a-divider type="vertical" class="info-title" dashed>井A1信息</a-divider>
              <a-descriptions bordered>
                <a-descriptions-item :labelStyle="{'width':'12%'}" :contentStyle="{'width':'21%'}" label="采油厂机构：">
                  {{ dataModel.org_name_a1 }}
                </a-descriptions-item>
                <a-descriptions-item label="单位名称：">{{ dataModel.org_name_a2 }}</a-descriptions-item>
                <a-descriptions-item label="标准井名：">{{ dataModel.well_legal_name }}</a-descriptions-item>
                <a-descriptions-item label="地理位置描述：" :span="3">{{ dataModel.geo_description }}</a-descriptions-item>
                <a-descriptions-item label="构造位置描述：" :span="3">{{ dataModel.structure_pos }}</a-descriptions-item>
                <a-descriptions-item label="创建/更新日期：">
                  {{ dataModel.update_date_fmt == null ? dataModel.create_date_fmt : dataModel.update_date_fmt }}
                </a-descriptions-item>
                <a-descriptions-item label="井筒生命阶段：">{{ dataModel.phase }}</a-descriptions-item>
                <a-descriptions-item label="通用井筒名：">{{ dataModel.wellbore_common_name }}</a-descriptions-item>
                <a-descriptions-item label="目的层：">{{ dataModel.target_formation }}</a-descriptions-item>
                <a-descriptions-item label="审定测量深度：">
                  {{ dataModel.authorized_md }}
                  <template v-if="dataModel.authorized_md">m</template>
                </a-descriptions-item>
                <a-descriptions-item label="审定真垂直深度：">{{ dataModel.authorized_tvd }}
                  <template v-if="dataModel.authorized_tvd">m</template>
                </a-descriptions-item>

                <a-descriptions-item label="井底测量深度：">{{ dataModel.bh_md }}
                  <template v-if="dataModel.bh_md">m</template>
                </a-descriptions-item>
                <a-descriptions-item label="井底位置描述信息：" :span="2">{{
                    dataModel.geo_description_bh
                  }}
                </a-descriptions-item>
                <a-descriptions-item label="井底真垂直深度：">{{ dataModel.bh_tvd }}
                  <template v-if="dataModel.bh_tvd">m</template>
                </a-descriptions-item>
                <a-descriptions-item label="相对于参考面的造斜点深度：">{{ dataModel.ko_md }}
                  <template v-if="dataModel.ko_md">m</template>
                </a-descriptions-item>
                <a-descriptions-item label="实际造斜点真垂直深度：">{{ dataModel.ko_tvd }}
                  <template v-if="dataModel.ko_tvd">m</template>
                </a-descriptions-item>
                <a-descriptions-item label="地质单元：">{{ dataModel.project_name }}</a-descriptions-item>
                <a-descriptions-item label="单元类型：">{{ dataModel.project_type }}</a-descriptions-item>
                <a-descriptions-item label="单元等级：">{{ dataModel.project_level }}</a-descriptions-item>
                <a-descriptions-item label="备注：" :span="3">{{ dataModel.remarks }}</a-descriptions-item>
              </a-descriptions>
              <a-divider type="vertical" class="info-title" dashed>井盆地凹陷信息</a-divider>
              <a-descriptions bordered>
                <a-descriptions-item :labelStyle="{'width':'12%'}" :contentStyle="{'width':'21%'}" label="标准盆地：">
                  {{ dataModel.bz_basin }}
                </a-descriptions-item>
                <a-descriptions-item label="标准地陷：">{{ dataModel.bz_depression }}</a-descriptions-item>
                <a-descriptions-item label="标准凹陷：">{{ dataModel.bz_depressed }}</a-descriptions-item>
                <a-descriptions-item label="标准构造带：">{{ dataModel.bz_structural_belt }}</a-descriptions-item>
                <a-descriptions-item label="标准区块：">{{ dataModel.bz_qkdy }}</a-descriptions-item>
                <a-descriptions-item label="标准组织机构：">{{ dataModel.bz_org_name }}</a-descriptions-item>
                <a-descriptions-item label="标准作业区名：">{{ dataModel.bz_dwmc }}</a-descriptions-item>
              </a-descriptions>
            </div>
            <div id="jsjgtp" style="flex:1;">
              <a-divider type="vertical" class="info-title" style="margin-top: 0px" dashed>
                井身结构图片（{{ dataModel.well_common_name }}）</a-divider>
              <ChartImage ref="chartImageRef" :wellname="dataModel.well_common_name" style="margin-left: 10px"></ChartImage>

              <a-divider type="vertical" class="info-title" dashed>相关文档</a-divider>
              <div style="margin-left:10px;border:1px solid #f0f0f0;padding:5px;">
                <a-input-search
                  v-model:value="fileOptions.docKey"
                  placeholder="查找文档" allow-clear
                />
                <div class="files-type">
                  <a-checkable-tag color="processing"
                                   :checked="fileOptions.selectBusinessType.length==0||fileOptions.selectBusinessType.length==fileOptions.businessType.length"
                                   @change="() => fileOptions.selectBusinessType=[]">全部
                  </a-checkable-tag>
                  <template v-for="tag in fileOptions.businessType">
                    <a-checkable-tag color="processing"
                                     :checked="fileOptions.selectBusinessType.includes(tag)"
                                     @change="checked => onBusTypeChange(checked,tag)">{{ tag }}
                    </a-checkable-tag>
                  </template>
                </div>
                <div style="max-height:990px;overflow-y:scroll;padding:0px 10px;">
                  <a-list item-layout="horizontal" :data-source="dataIndexList">
                    <template #renderItem="{ item }">
                      <a-list-item v-if="(item.file_name.indexOf(fileOptions.docKey)>-1||fileOptions.docKey=='')
                      &&(fileOptions.selectBusinessType.length==0||fileOptions.selectBusinessType.includes(item.file_business_type))">
                        <template #actions>
                          <PlusOutlined v-if="!item.isApply" @click="onAddCart(item)" title="加入购物车"
                                        :style="{fontSize: '16px', color: '#08c'}"/>
                          <a-button type="link" @click="downFile(item)" v-if="item.isDown" danger>下载</a-button>
                          <filePreview :fileName="item.file_name" :filePath="item.storage_path" :title="item.well_common_name"></filePreview>
                        </template>
                        <a-list-item-meta
                          :description="item.file_business_type">
                          <template #title>
                            {{ item.file_name }}
                          </template>
                          <template #avatar>
                            <img src="~@/assets/images/file.png"/>
                          </template>
                        </a-list-item-meta>
                      </a-list-item>
                    </template>
                  </a-list>
                </div>
              </div>
            </div>
          </div>
        </a-card>
        <a-card id="csls" :bordered="false" :headStyle="cardSettings.cardHeadStyle" class="card-detail">
          <template #title>
            <div slot="title" style="width:100%" @click="cardSettings.cardTest.expand=!cardSettings.cardTest.expand">测试历史
            </div>
          </template>
          <template #extra>
            <UpSquareOutlined v-if="cardSettings.cardTest.expand" @click="cardSettings.cardTest.expand=false"
                              :style="cardSettings.buttonStyle"/>
            <DownSquareOutlined v-else @click="cardSettings.cardTest.expand=true"
                                :style="cardSettings.buttonStyle"/>
          </template>
          <div v-if="cardSettings.cardTest.expand">
            <p v-if="testHistoryList.length>0" class="info-body">本井共实施
              <template v-for="it in testHistorySummary">
                <span>{{ it.testing_num }}</span>次{{ it.testing_name }},
              </template>
              <span>{{ lastTestHistory.testing_date }}</span>进行最近一次<span>{{ lastTestHistory.testing_name }}</span>，
              <span>{{ lastTestHistory.construction_description }}</span>
            </p>
            <br/>
            <a-table :columns="testHistoryColumns" :data-source="testHistoryList" :scroll="{ x:'100%', y: 500 }"
                     :pagination="testHistoryPage"
                     @change="handleTestHistoryChange" @resizeColumn="handleResizeColumn" :rowClassName = "rowClassName"
                     bordered>
            </a-table>
          </div>
        </a-card>
        <a-card id="fxhy" :bordered="false" :headStyle="cardSettings.cardHeadStyle" class="card-detail">
          <template #title>
            <div slot="title" style="width:100%"
                 @click="cardSettings.cardAnalysis.expand=!cardSettings.cardAnalysis.expand">分析化验
            </div>
          </template>
          <template #extra>
            <UpSquareOutlined v-if="cardSettings.cardAnalysis.expand" @click="cardSettings.cardAnalysis.expand=false"
                              :style="cardSettings.buttonStyle"/>
            <DownSquareOutlined v-else @click="cardSettings.cardAnalysis.expand=true"
                                :style="cardSettings.buttonStyle"/>
          </template>
          <div v-if="cardSettings.cardAnalysis.expand">
            <p class="info-body">
              <template v-for="it in analyticalAssaysSummary">
                {{ it.item_code }}<span>{{ it[it.item_code] }}</span>组、
              </template>
            </p>
            <br>
            <a-table :columns="analyticalAssaysColumns" :data-source="analyticalAssaysList" :scroll="{ x:'100%', y: 500 }"
                     :pagination="analyticalAssaysPage"
                     @change="handleAnalyticalAssaysChange" @resizeColumn="handleResizeColumn" :rowClassName = "rowClassName"
                     bordered>
            </a-table>
          </div>
        </a-card>
        <a-card id="zyjs" :bordered="false" :headStyle="cardSettings.cardHeadStyle" class="card-detail">
          <template #title>
            <div slot="title" style="width:100%" @click="cardSettings.cardWork.expand=!cardSettings.cardWork.expand">
              作业简史（业务过程）
            </div>
          </template>
          <template #extra>
            <UpSquareOutlined v-if="cardSettings.cardWork.expand" @click="cardSettings.cardWork.expand=false"
                              :style="cardSettings.buttonStyle"/>
            <DownSquareOutlined v-else @click="cardSettings.cardWork.expand=true"
                                :style="cardSettings.buttonStyle"/>
          </template>
          <div v-if="cardSettings.cardWork.expand">
            <p class="info-body" v-if="historyAssignmentList.length>0">
              井实施井下作业施工<span>{{ historyAssignmentCount }}</span>次，其中：
              <template v-for="it in historyAssignmentSummary">
                {{ it.test_processes_name }}<span>{{ it.testing_num }}</span>次、
              </template>
              <span v-if="lastHistoryAssignment.test_processes_name">{{
                  lastHistoryAssignment.start_time
                }}{{ lastHistoryAssignment.test_processes_name }}，</span>
              <span>{{
                  lastHistoryAssignment.test_processes_name
                }}</span><span v-if="lastHistoryAssignment.well_production_sections">井段{{
                lastHistoryAssignment.well_production_sections
              }}</span></p>
            <br/>
            <a-table :columns="historyAssignmentColumns" :data-source="historyAssignmentList" :scroll="{ x:'100%', y: 500 }"
                     :pagination="false" @resizeColumn="handleResizeColumn" :rowClassName = "rowClassName"
                     bordered>
            </a-table>
          </div>
        </a-card>
        <a-card id="cjjs" :bordered="false" :headStyle="cardSettings.cardHeadStyle" class="card-detail">
          <template #title>
            <div slot="title" style="width:100%" @click="cardSettings.cardExplain.expand=!cardSettings.cardExplain.expand">
              测井解释
            </div>
          </template>
          <template #extra>
            <UpSquareOutlined v-if="cardSettings.cardExplain.expand" @click="cardSettings.cardExplain.expand=false"
                              :style="cardSettings.buttonStyle"/>
            <DownSquareOutlined v-else @click="cardSettings.cardExplain.expand=true"
                                :style="cardSettings.buttonStyle"/>
          </template>
          <div v-if="cardSettings.cardExplain.expand">
              <ColumnsSetting style="display: flex;justify-content: flex-end;"
                              :table-columns="boreholeInterColumns" :checked-table-columns="checkBoreholeInterColumns"
                                @on-check="boreholeInterColumnsCheckSub"></ColumnsSetting>
              <a-table :columns="checkBoreholeInterColumns" :data-source="boreholeInterList" :scroll="{ x:'1500', y: 500 }"
                     :pagination="false" @resizeColumn="handleResizeColumn" :rowClassName = "rowClassName"
                     bordered>
              </a-table>
          </div>
        </a-card>
        <a-card id="gisdt" :bordered="false" :headStyle="cardSettings.cardHeadStyle" class="card-detail">
      <template #title>
        <div slot="title" style="width:100%" @click="cardSettings.cardGIS.expand=!cardSettings.cardGIS.expand">GIS地图
        </div>
      </template>
      <template #extra>
        <UpSquareOutlined v-if="cardSettings.cardGIS.expand" @click="cardSettings.cardGIS.expand=false"
                          :style="cardSettings.buttonStyle"/>
        <DownSquareOutlined v-else @click="cardSettings.cardGIS.expand=true"
                            :style="cardSettings.buttonStyle"/>
      </template>
      <div v-if="cardSettings.cardGIS.expand">
        <div style="width:100%;height: 500px;margin-top:15px;">
          <ChartMap :datas="mapDatas"></ChartMap>
        </div>
      </div>
    </a-card>
      </a-layout-content>
    </a-layout>
  </div>
</template>
<script lang="ts">
import {ref, defineComponent, toRefs, reactive, watch} from 'vue';
import {get, postData} from "@/api/common";
import {useTabsViewStore} from "@/store/modules/tabsView";
import dayjs from "dayjs";
import {useRoute} from "vue-router";
import router from "@/router";
import * as columns from './columns';
import {boreholeInterColumns} from "./columns";
import ChartProdDynmics from '@/components/basic/chart/chart-prod-dynamics.vue'
import ChartMap from '@/components/basic/chart/chart-map.vue'
import filePreview from '@/components/basic/file-preview/index.vue'
import {download} from "@/utils/downloadFile";
import {getPaginationTotalTitle} from "@/utils/common";
import type {TableProps} from "ant-design-vue";
import {message} from "ant-design-vue";
import ChartImage from "@/components/basic/chart/chart-image.vue";
import ColumnsSetting from "@/components/common/ColumnsSetting.vue";

export default defineComponent({
  name: 'wellinfoDetail',
  components: {ChartImage, ChartProdDynmics, ChartMap, filePreview, ColumnsSetting},
  setup() {
    const tabsViewStore = useTabsViewStore();
    const route = useRoute();
    const chartImageRef = ref();
    const cardSettings = ref({
      cardHeadStyle: {fontWeight: 'bold'},
      buttonStyle: {fontSize: '20px', cursor: 'pointer'},
      cardSummary: {expand: true},
      cardChat: {expand: true},
      cardBaseInfo: {expand: true},
      cardExplain: {expand: true},
      cardFile: {expand: true},
      cardTest: {expand: true},
      cardAnalysis: {expand: true},
      cardWork: {expand: true},
      cardGIS: {expand: true}
    })
    const wellId = ref(history.state.params?.id);

    const checkBoreholeInterColumns: any = ref(boreholeInterColumns.value);

    const testHistoryPage = ref({
      total: 0,
      current: 1,
      pageSize: 10,
      showSizeChanger: true,
      showTotal: total => getPaginationTotalTitle(total)
    });

    const handleTestHistoryChange: TableProps['onChange'] = (
      pag: { pageSize: number; current: number },
    ) => {
      testHistoryPage.value.current = pag.current;
      testHistoryPage.value.pageSize = pag.pageSize;
      loadTestHistoryData();
    };

    const loadTestHistoryData=()=> {
      let id = history.state.params?.id ?? wellData.dataModel.well_id;
      get('wellInfo/getTestHistoryList', {
        page: testHistoryPage.value.current,
        rows: testHistoryPage.value.pageSize,
        well_id: id
      }).then(result => {
        wellData.testHistoryList = result.list;
        testHistoryPage.value.total = result.total;
      })
    }

    const analyticalAssaysPage = ref({
      total: 0,
      current: 1,
      pageSize: 10,
      showSizeChanger: true,
      showTotal: total => getPaginationTotalTitle(total)
    });

    const handleAnalyticalAssaysChange: TableProps['onChange'] = (
      pag: { pageSize: number; current: number },
    ) => {
      analyticalAssaysPage.value.current = pag.current;
      analyticalAssaysPage.value.pageSize = pag.pageSize;
      loadAnalyticalAssaysData();
    };

    const loadAnalyticalAssaysData=()=> {
      let id = history.state.params?.id ?? wellData.dataModel.well_id;
      get('wellInfo/getAnalyticalAssaysList', {
        page: analyticalAssaysPage.value.current,
        rows: analyticalAssaysPage.value.pageSize,
        well_id: id
      }).then(result => {
        wellData.analyticalAssaysList = rowSpan(result.list);
        analyticalAssaysPage.value.total = result.total;
      })
    }

    const fileOptions = reactive({
      docKey: '',
      businessType: [] as any[],
      selectBusinessType: [] as any[]
    })

    const onBusTypeChange=(checked, it) =>{
      if (checked) {
        fileOptions.selectBusinessType.push(it);
      } else {
        fileOptions.selectBusinessType.splice(fileOptions.selectBusinessType.indexOf(it), 1);
      }
      console.log(checked, it);
    }

    watch(
      () => cardSettings,
      () => {
        let id = history.state.params?.id ?? wellData.dataModel.well_id;
        postData('wellInfo/saveExpendSetting', {well_id: id, setting_json: JSON.stringify(cardSettings.value)});
      }, {deep: true, immediate: false}
    );
    const wellData = reactive({
      dataModel: {well_id: null},
      boreholeInterList: [],
      testHistoryList: [],
      testHistorySummary: [],
      lastTestHistory: {},
      analyticalAssaysList: [] as any[],
      analyticalAssaysSummary: [],
      historyAssignmentList: [],
      historyAssignmentSummary: [],
      lastHistoryAssignment: {},
      historyAssignmentCount: 0,
      dataIndexList: [] as any[],
      mapDatas: [] as any
    });

    const loadData = async (id) => {
      if (id == undefined) {
        return;
      }
      loadTestHistoryData();
      loadAnalyticalAssaysData();

      get('wellInfo/getWellInfo', {well_id: id}).then(data => {
        wellData.dataModel = data.dataModel;
        wellData.boreholeInterList = data.boreholeInterList;
        wellData.testHistorySummary = data.testHistorySummary;
        wellData.lastTestHistory = data.lastTestHistory ?? {};
        wellData.analyticalAssaysSummary = data.analyticalAssaysSummary;
        wellData.historyAssignmentList = data.historyAssignmentList;
        wellData.historyAssignmentSummary = data.historyAssignmentSummary;
        wellData.lastHistoryAssignment = data.lastHistoryAssignment ?? {};
        wellData.dataIndexList = checkApplyFile(data.dataIndexList);
        wellData.historyAssignmentCount = wellData.historyAssignmentSummary.reduce((total, it: any) => total + it.testing_num, 0);
        wellData.mapDatas = [{
          well_id: wellData.dataModel.well_id,
          well_common_name: data.dataModel.well_common_name,
          geo_description: data.dataModel.geo_description,
          x: data.dataModel.well_coordinates_x,
          y: data.dataModel.well_coordinates_y
        }];

        fileOptions.businessType = wellData.dataIndexList.map(x => x.file_business_type);
        fileOptions.businessType = Array.from(new Set(fileOptions.businessType));
        if(chartImageRef.value){
          chartImageRef.value.getImageUrl(data.dataModel.well_common_name);
        }
      })
      get('wellInfo/getExpendSetting', {wellId: id}).then(data => {
        if (data != null) {
          cardSettings.value = JSON.parse(data.setting_json);
        }
      })
    }

    const checkApplyFile=(dataIndexList: any[]) =>{
      let applyFileList = getStoreFiles();
      dataIndexList.forEach(it => {
        if (!it.isApply) {
          it.isApply = applyFileList.filter(file => file.well_common_name == it.well_common_name && file.file_name == it.file_name).length > 0;
        }
      })
      return dataIndexList;
    }

    const getStoreFiles=()=> {
      let applyFileList = new Array();
      let storeList = localStorage.getItem("applyFileList");
      if (storeList != null) {
        applyFileList = JSON.parse(storeList);
      }
      return applyFileList;
    }

    const rowSpan=(list: any[]) =>{
      for (let i = 0; i < list.length; i++) {
        list[i].rowSpan = getRowSpan(list[i].item_code, i + 1, list);
      }
      return list;
    }

    const getRowSpan=(itemCode, starIndex, list: any[])=> {
      let rowSpan = 1;
      for (let i = starIndex; i < list.length; i++) {
        if (list[i].item_code != itemCode) {
          break;
        }
        if (list[i].rowSpan == 0) {
          break;
        }
        ++rowSpan;
        list[i].rowSpan = 0;
      }
      return list[starIndex - 1].rowSpan == 0 ? 0 : rowSpan;
    }

    const downFile = (record: any) => {
      download(record.storage_path, record.file_name);
    };
    const onAddCart = (file) => {
      let applyFileList = new Array();
      let storeList = localStorage.getItem("applyFileList");
      if (storeList != null) {
        applyFileList = JSON.parse(storeList);
      }
      applyFileList.push({
        well_common_name: file.well_common_name,
        file_name: file.file_name,
        storage_path: file.storage_path
      });
      localStorage.setItem("applyFileList", JSON.stringify(applyFileList));
      file.isApply = true;
      message.info('成功加入购物车');
    }
    const onClose = () => {
      tabsViewStore.closeCurrentTab(route);
      router.back();
    };

    const rowClassName = (record,index) => {
      console.log(record);
      return index % 2 === 0 ? 'even' : 'odd';
    }

    //#regin 锚点
    const getContainer = () => {
      return document.querySelector(".tabs-view-content")
      // return document.querySelector("#wellInfoDetail")
    }

    const handleClickAnchor = (e: any, link: any) => {
      console.log(e)
      if (link.href) {
        const element = document.querySelector(link.href);
        element && element.scrollIntoView({block: 'start', behavior: 'smooth', alignToTop: 'false'});
      }
    }

    const steps = ref([
      {id: '#jsjj', title: '井史简介', content: '井史简介'},
      {id: '#scdt', title: '生产动态', content: '生产动态'},
      {id: '#jbxx', title: '基本信息', content: '基本信息'},
      {id: '#jsjgtp', title: '井身结构图片', content: '井身结构图片'},
      {id: '#csls', title: '测试历史', content: '测试历史'},
      {id: '#fxhy', title: '分析化验', content: '分析化验'},
      {id: '#zyjs', title: '作业简史（业务过程）', content: '作业简史（业务过程）'},
      {id: '#cjjs', title: '测井解释', content: '测井解释'},
      {id: '#gisdt', title: 'GIS地图', content: 'GIS地图'},
    ]);
    //#endregin

    // 字段展示列选择完毕
    const boreholeInterColumnsCheckSub = (columnsKeys: Array<string>) => {
      // 从原始表格定义数据中过滤出已选择的字段
      checkBoreholeInterColumns.value = boreholeInterColumns.value.filter((item: any) => columnsKeys.includes(item.key));
    }

    return {
      ...toRefs(wellData),
      loadData, cardSettings,
      onClose, ...columns, analyticalAssaysPage, handleAnalyticalAssaysChange, onAddCart, rowClassName,
      dayjs, wellId, fileOptions, downFile, onBusTypeChange, handleTestHistoryChange, testHistoryPage,
      handleResizeColumn: (w, col) => {
        col.width = w;
      },
      chartImageRef, boreholeInterColumns, checkBoreholeInterColumns , boreholeInterColumnsCheckSub,
      getContainer, handleClickAnchor, steps
    };
  },
  created() {
    const id = history.state.params?.id;
    if (id == undefined) {
      this.onClose();
    }
    this.loadData(id);
  }
});
</script>

<style lang="less">
#wellInfoDetail{
  .ant-layout-sider{
    background-color: white;
  }

  .anchor{
    margin: 0px 20px;
    position: fixed;
    top: 200px;
  }

  .even {
    background-color: #f2f2f2;
  }

  .odd {
    background-color: #ffffff;
  }

  .card-detail {
    width: 100%;
    margin-top: 10px;

    a {
      color: #1890ff;
    }

    .ant-card-head-title {
      font-weight: bold;
      color: #40a9ff;
      font-size: 20px;
    }

    .ant-card-head {
      padding: 0px 10px;
      height: 35px;
      cursor: pointer;
    }

    .ant-card-head-wrapper {
      height: 35px;
      margin-top: 5px;
    }
    .checkbox-group{
      width: 100%;
      text-align: right;
      padding: 5px 0px;
    }
  }

  .files-type {
    margin-top: 10px;

    span {
      color: #8e9ae1;
      border: 1px solid #c6ccf0;
      padding: 3px 5px;
      margin-bottom: 5px;
    }

    .ant-tag-checkable-checked, .ant-tag-checkable-checked:active {
      background-color: #8e9ae1;
      color: #ffffff;
    }
  }

  .info-body {
    line-height: 40px;

    span {
      color: #1890ff;
      font-weight: 600;
      font-size: 25px;
    }
  }

  .info-title {
    border-color: #7cb305;
    margin: 15px;
    font-weight: bold;
  }
}
</style>
