<template>
  <div class="query-index" >
    <div v-if="showOverlay" style="position: fixed;top: 0;left: 0;width: 100vw;height: 100vh;background-color: rgba(0, 0, 0, 0.5);z-index: 999;  "></div>
    <div class="query-index-tree" v-if="showTree" data-v-step="1"
         :style="showOverlay&&curStepVal==1?'z-index:1000;background:white;':''">
      <div class="query-index-tree-search">
        <a-tabs v-model:activeKey="activeTab" @change="tabChange" style="width:97%;">
          <a-tab-pane key="1" tab="组织架构目录" >
          </a-tab-pane>
          <a-tab-pane key="2" tab="地质单元目录" forceRender="true">
          </a-tab-pane>
        </a-tabs>
        <DoubleLeftOutlined @click="changeTree()"/>
      </div>
      <div style="margin-top: -15px">
        <a-input-search
          v-model:value="subjectTrees.searchStr"
          placeholder="查找目录..." allow-clear
          @search="searchTree"
        />
      </div>
      <div class="query-index-tree-box">
        <a-tree
          ref="treeRef"
          :show-line="true" blockNode="true"
          :tree-data="subjectTrees.data"
          v-model:expandedKeys="subjectTrees.expandedKeys"
          v-model:selectedKeys="subjectTrees.selectedKeys"
          :replace-fields="replaceFields"
          :autoExpandParent="subjectTrees.autoExpandParent"
          @expand="treeOnExpand" @select="treeOnSelect">
          <template #switcherIcon="{ switcherCls }">
            <caret-down-outlined style="font-size:20px;" :class="switcherCls"/>
          </template>
          <template #title="{ label,value,children }">
                    <span v-if="label!=null&&label.indexOf(subjectTrees.searchStr) > -1">
                      {{ label.substr(0, label.indexOf(subjectTrees.searchStr)) }}
                      <span style="color: #f50">{{ subjectTrees.searchStr }}</span>
                      {{ label.substr(label.indexOf(subjectTrees.searchStr) + subjectTrees.searchStr.length) }}
                    </span>
            <span v-else>{{ label }}</span>
          </template>
        </a-tree>
      </div>
    </div>
    <div class="query-index-close" v-else>
      <DoubleRightOutlined @click="showTree=true;colspan=8;"/>
    </div>
    <v-tour name="wellInfoTour" style="z-index: 1000;" :steps="steps" :options="myOptions" :callbacks="myCallbacks"></v-tour>

    <div class="query-index-content" >
      <div class="query-index-form" >
        <a-form ref="formRef" name="fromQuery"
                class="ant-advanced-search-form"
                :label-col="labelCol"
                :model="formState">
          <a-row :gutter="24" class="query-index-row" >
            <a-col :span="6">
              <a-form-item name="well_common_name" label="井名:">
                <a-input id="wellName" v-model:value="formState.well_common_name"/>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item name="well_type" label="井型:">
                <a-tree-select
                  v-model:value="formState.well_type"
                  show-search
                  allow-clear
                  tree-line
                  :tree-data="wellTypeTree"
                  tree-node-filter-prop="label">
                </a-tree-select>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item name="well_type" label="井别:">
                <a-tree-select
                  v-model:value="formState.well_purpose"
                  show-search
                  allow-clear
                  tree-line
                  :tree-data="wellPurposeTree"
                  tree-node-filter-prop="label">
                </a-tree-select>
              </a-form-item>
            </a-col>
            <a-col :span="6" :style="showOverlay && curStepVal==2?'z-index:1000;background:white;display:inline-block;width:150px;height:32px;position:relative;':'display:inline-block;width:450px;height:32px;'">
              <MenuOutlined @click="changeQuery(true)" v-if="!showQuery" data-v-step="2"  />
              <LineOutlined @click="changeQuery(false)" v-else/>
              <a-button type="primary" html-type="submit" @click="onQuery" style="margin-left: 10px;">查询</a-button>
              <a-button html-type="submit"
                        @click="() => {resetFields();formState.ref_date=new Date(); onQuery()}"
                        style="margin-left: 10px;">重置
              </a-button>
              <QuestionCircleOutlined title="查看帮助" @click="showHelp"
                                      :style="{fontSize: '20px',display:'contents',cursor:'pointer'}"/>
            </a-col>
          </a-row>
          <a-row :gutter="24" class="query-index-row" v-if="showQuery">
            <a-col :span="18">
              <a-form-item name="well_id" label="组织机构:">
                <a-tree-select
                  v-model:value="formState.orgList"
                  show-search
                  allow-clear
                  multiple
                  tree-line
                  :tree-data="filterOrgTree(subjectTrees.organizationTree)"
                  tree-node-filter-prop="label"
                  @change="onOrgTreeChange"
                >
                </a-tree-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24" class="query-index-row" v-if="showQuery">
            <a-col :span="18">
              <a-form-item name="spud_date_begin" label="地质单元:">
                <a-tree-select
                  v-model:value="formState.unitList"
                  show-search
                  allow-clear
                  multiple
                  tree-line
                  :tree-data="filterUnitTree(subjectTrees.constructUnitTree)"
                  tree-node-filter-prop="label" @change="onUnitTreeChange">
                </a-tree-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="24" class="query-index-row" v-if="showQuery">
            <a-col :span="6">
              <a-form-item name="spud_date_begin" label="开钻日期:">
                <a-range-picker :key="formState.ref_date" format="YYYY-MM-DD" :placeholder="['开始日期', '结束日期']"
                                @change="(d)=>{onRangeChange(d,'spud_date_begin','spud_date_end')}"/>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item name="completion_date_begin" label="完井日期:">
                <a-range-picker :key="formState.ref_date" format="YYYY-MM-DD" :placeholder="['开始日期', '结束日期']"
                                @change="(d)=>{onRangeChange(d,'completion_date_begin','completion_date_end')}"/>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item name="oil_prod_begin_date_begin" label="投产日期:">
                <a-range-picker :key="formState.ref_date" format="YYYY-MM-DD" :placeholder="['开始日期', '结束日期']"
                                @change="(d)=>{onRangeChange(d,'oil_prod_begin_date_begin','oil_prod_begin_date_end')}"/>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row class="edit-operation" style="width:450px;float:right;"  data-v-step="3">
            <a-col :span="24"  :style="showOverlay && curStepVal==3?'text-align: right;z-index:1000;background:white;':'text-align: right;'">
              <a-checkbox-group v-model:value="showColumnType" @change="onCheckboxChange">
                <a-row>
                  <a-col :span="8">
                    <a-checkbox value="oil">显示产油</a-checkbox>
                  </a-col>
                  <a-col :span="8">
                    <a-checkbox value="gas">显示产气</a-checkbox>
                  </a-col>
                  <a-col :span="8">
                    <a-checkbox value="water">显示产水</a-checkbox>
                  </a-col>
                </a-row>
              </a-checkbox-group>
              <a-radio-group v-model:value="viewModel" style="text-align: left">
                <a-radio-button value="list">
                  <UnorderedListOutlined/>
                  列表
                </a-radio-button>
                <a-radio-button value="card">
                  <TableOutlined/>
                  卡片
                </a-radio-button>
              </a-radio-group>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div  :style="showOverlay&&curStepVal==4?'flex-grow: 1;overflow: auto;height:auto;z-index:999;background:white;':'flex-grow: 1;overflow: auto;height:auto;'">
        <a-spin :spinning="loading">
          <div class="query-index-table" data-v-step="4" v-if="viewModel=='list'" >
            <a-table :columns="filterColumns" :data-source="data" :scroll="{ x:'100%', y: '100%' }"
                     :row-key="record=>record.tempId" :pagination="false" @resizeColumn="handleResizeColumn"
                     bordered>
              <template #bodyCell="{ column,record }">
                <template v-if="column.dataIndex === 'oil'">
                  <div style="height:25px">
                    <ChartCell :timeType="('month')" :dataType="('oil')" :wellId="record.well_id"></ChartCell>
                  </div>
                </template>
                <template v-if="column.dataIndex === 'gas'">
                  <div style="height:25px">
                    <ChartCell :timeType="('month')" :dataType="('gas')" :wellId="record.well_id"></ChartCell>
                  </div>
                </template>
                <template v-if="column.dataIndex === 'water'">
                  <div style="height:25px">
                    <ChartCell :timeType="('month')" :dataType="('vol')" :wellId="record.well_id"></ChartCell>
                  </div>
                </template>
                <template v-if="column.key === 'well_common_name'">
                  <a-button type="link" size="small" @click="detail(record.well_id)">{{
                      record.well_common_name
                    }}
                  </a-button>
                </template>
                <template v-if="column.key === 'operation'">
                  <a-button type="link" size="small" @click="showDoc(record.well_id)">相关文档</a-button>
                </template>
              </template>
            </a-table>
          </div>
          <div class="query-index-table" v-else >
            <a-row :gutter="[24,8]">
              <a-col :span="colspan" v-for="item in data">
                <a-card :title="'井名：'+item.well_common_name" class="ant-card-index" bodyStyle="padding: 10px;">
                  <template #extra>
                    <a-button type="link" @click="detail(item.well_id)">查看详情</a-button>
                    <a-button type="link" @click="showDoc(item.well_id)">相关文档</a-button>
                  </template>
                  <table class="well-card-table">
                    <tr>
                      <th>井型：</th>
                      <td>{{ item.well_type }}</td>
                      <th>状态：</th>
                      <td name="current_state_name">{{ item.current_state_name }}</td>
                    </tr>
                    <tr>
                      <th>开钻日期：</th>
                      <td name="spud_date">{{ item.spud_date }}</td>
                      <th>含水率：</th>
                      <td name="water_cut">
                        <span style="padding:2px 10px;" :class="getTdColor(item.water_cut)">{{
                            item.water_cut
                          }}</span>
                      </td>
                    </tr>
                    <tr>
                      <th>开始采油日期：</th>
                      <td name="oil_prod_begin_date">{{ item.oil_prod_begin_date }}</td>
                      <th>最近采油日期：</th>
                      <td name="oil_prod_recent_date">{{ item.oil_prod_recent_date }}</td>
                    </tr>
                    <tr v-if="showColumnType.includes('oil')">
                      <th>最近月产油量：</th>
                      <td name="oil_prod_mon">
                        {{ item.oil_prod_mon == null ? "" : (numberToCurrencyNo(item.oil_prod_mon) + "t") }}
                      </td>
                      <td colspan="2" rowspan="2">
                        <div style="height:25px">
                          <ChartCell :timeType="('month')" :dataType="('oil')" :wellId="item.well_id"
                                     :lineColor="('#E63038')"></ChartCell>
                        </div>
                      </td>
                    </tr>
                    <tr v-if="showColumnType.includes('oil')">
                      <th>累产油量：</th>
                      <td name="oil_prod_year">
                        {{ item.oil_prod_year == null ? "" : (numberToCurrencyNo(item.oil_prod_year) + "t") }}
                      </td>
                    </tr>
                    <tr v-if="showColumnType.includes('gas')">
                      <th>最近月产气量：</th>
                      <td name="gas_prod_mon">
                        {{ item.gas_prod_mon == null ? "" : (numberToCurrencyNo(item.gas_prod_mon) + "m³") }}
                      </td>
                      <td colspan="2" rowspan="2">
                        <div style="height:25px">
                          <ChartCell :timeType="('month')" :dataType="('gas')" :wellId="item.well_id"></ChartCell>
                        </div>
                      </td>
                    </tr>
                    <tr v-if="showColumnType.includes('gas')">
                      <th>累产气量：</th>
                      <td name="gas_prod_year">
                        {{ item.gas_prod_year == null ? "" : (numberToCurrencyNo(item.gas_prod_year) + "m³") }}
                      </td>
                    </tr>
                    <tr v-if="showColumnType.includes('water')">
                      <th>最近注水量：</th>
                      <td name="water_prod_mon">
                        {{ item.water_prod_mon == null ? "" : (numberToCurrencyNo(item.water_prod_mon) + "t") }}
                      </td>
                      <td colspan="2" rowspan="2">
                        <div style="height:25px">
                          <ChartCell :timeType="('month')" :dataType="('vol')" :wellId="item.well_id"></ChartCell>
                        </div>
                      </td>
                    </tr>
                    <tr v-if="showColumnType.includes('water')">
                      <th>累注水量：</th>
                      <td name="water_prod_year">
                        {{ item.water_prod_year == null ? "" : (numberToCurrencyNo(item.water_prod_year) + "10kt") }}
                      </td>
                    </tr>
                  </table>
                </a-card>
              </a-col>
            </a-row>
          </div>
          <a-pagination :page-size-options="pagination.pageSizeOptions" show-size-changer
                        :total="pagination.total" style="float: right;margin-top: 10px;"
                        :current="pagination.current"  :pageSize="pagination.pageSize"
                        :show-total="total => `共 ${total} 条`"
                        @change="(current)=>handleTableChange({ current: current,pageSize: pagination.pageSize })"
                        @showSizeChange="(current,pageSize)=>handleTableChange({ current: current,pageSize: pageSize })"/>
        </a-spin>
      </div>
      <div :style="showOverlay&&curStepVal==5?'flex-grow: 1;overflow: auto;z-index:999;background:white;':'flex-grow: 1;overflow: auto;'" style="width:100%;height: 500px;" >
        <ChartMap ref="chartMapRef" :isSearch="(true)" data-v-step="5"></ChartMap>
      </div>
    </div>
    <a-modal v-model:visible="isShowDoc" title="相关文档" width="800px" :footer="null" @onCancel="isShowDoc=false">
      <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:300px;overflow-y:scroll;margin-top:10px;">
        <a-list item-layout="horizontal" :data-source="docList">
          <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"></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>
    </a-modal>
  </div>
</template>

<script lang="ts">
import {ref, defineComponent, computed, watch, reactive, getCurrentInstance} from 'vue';
import type {FormInstance} from 'ant-design-vue';
import {useRoute} from 'vue-router';
import {get, postData} from "@/api/common";
import {getPaginationTotalTitle} from "@/utils/common";
import {message} from 'ant-design-vue';
import type {TableProps} from "ant-design-vue";
import {useTabsViewStore} from "@/store/modules/tabsView";
import ChartCell from '@/components/basic/chart/chart-cell.vue'
import ChartMap from '@/components/basic/chart/chart-map.vue'
import {download} from "@/utils/downloadFile";
import {columns, filterColumns, formState, getTdColor} from './table';
import filePreview from '@/components/basic/file-preview/index.vue';
import {numberToCurrencyNo} from "@/utils/common";

export default defineComponent({
  name: 'wellinfoindex',
  components: {ChartCell, ChartMap, filePreview},
  setup() {

    const curTour = ref({});
    const route = useRoute();
    const expand = ref(false);
    const formRef = ref<FormInstance>();
    const loading = ref(false);
    const showQuery = ref(false);
    const selectedRowKeys = ref([]);
    const activeTab = ref("1");
    const colspan = ref(8);
    const showTree = ref(true);
    const isShowDoc = ref(false);
    const showColumnType = ref(['oil', 'gas', 'water']);
    const data = ref([]);
    const viewModel = ref("list");
    const tabsViewStore = useTabsViewStore();
    const docKey = ref('');
    const docList = ref<any>([]);
    const wellTypeList = ref([{label: "直井", value: "直井"}, {label: "定向井", value: "定向井"}, {label: "分支井", value: "分支井"}]);
    const wellPurposeList = ref([{label: "探井", value: "探井"}, {label: "开发井", value: "开发井"}, {label: "水井", value: "水井"}]);
    const chartMapRef = ref();

    const steps = reactive([
      {
        target:'[data-v-step="1"]',
        header:{
          title:'<div class="leftTriangle" style="position:absolute;right:28.5em;top:1.5em;"></div>' +
                '<div class="tipsTitle">引导1/5:</div>'
        },
        content:'<div class="tipsContent">可以切换目录查询</div>',
        params:{
          placement:'right'
        }
      },{
        target:'[data-v-step="2"]',
        header:{
          title:'<div class="rightTriangle" style="position:absolute;left:23.5em;top:1em;"></div>' +
                '<div class="tipsTitle" style="position:relative;left:-4.7em;">引导2/5:</div>',
        },
        content:'<div class="tipsContent" style="position:relative;left:-5em;">点击"☰"按钮展开更多查询</div>',
        params:{
          placement:'left'
        }
      },{
        target:'[data-v-step="3"]',
        header:{
          title:'<div class="rightTriangle" style="position:absolute;left:28.5em;top:1.5em;"></div>' +
                '<div class="tipsTitle">引导3/5:</div>',
        },
        content:'<div class="tipsContent">切换不同视图，也可勾选需要显示的列</div>',
        params:{
          placement:'left'
        }
      },{
        target:'[data-v-step="4"]',
        header:{
          title:'<div class="topTriangle" style="position:absolute;top:-2.5em;left:13em;"></div>' +
                '<div class="tipsTitle">引导4/5:</div>'
        },
        content:'<div class="tipsContent" >可移动表格数据列的顺序</div>',
        params:{
          placement:'bottom'
        }
      },{
        target:'[data-v-step="5"]',
        header:{
          title:'<div class="topTriangle" style="position:absolute;top:-2.5em;left:13em;"></div>' +
                '<div class="tipsTitle">引导5/5:</div>'
        },
        content:'<div class="tipsContent">地图显示当前列表的井所在位置</div>',
        params:{
          placement:'bottom'
        }
      }
    ]);

    const myOptions = reactive({
      dialogVisible:false,
      useKeyboardNavigation:false,
      labels:{
        buttonSkip:' 跳过引导 ',
        buttonPrevious:' 上一步 ',
        buttonNext:'下一步 ',
        buttonStop:' 明白了 '
      }
    });
    const showOverlay = ref(false);

    const curStepVal = ref(1);

    const myCallbacks = ref({
      onStart(){
        loadStyle();
      },
      onPreviousStep(){
        curStepVal.value -= 1;
        loadStyle();
      },
      onNextStep(){
        curStepVal.value += 1;
        loadStyle();
      },
      onStop:async function(){
        showOverlay.value = false;
        curStepVal.value = 1;
        const $input = document.getElementById('wellName');
        $input?.focus();
      }
    });

    function loadStyle(){
      setTimeout(()=>{
        const $divs = document.getElementsByClassName("v-step__buttons");
        for(let i=0;i < $divs.length;i++) {
          const div = $divs[i];
          if(curStepVal.value ==2){
            div.setAttribute("style","background-color:#4c8dff;color:white;height:3em;width:100%;" +
              "position: relative;top:-.2em;left:-5em;padding-top:0.4em;border-radius:0 0 10px 10px;");
          }else{
            div.setAttribute("style","background-color:#4c8dff;color:white;height:3em;width:100%;" +
              "position: relative;top:-0.2em;padding-top:0.4em;border-radius:0 0 10px 10px;");
          }
        }
        const $buttons = document.getElementsByClassName("v-step__button");
        for(let i=0;i < $buttons.length;i++) {
          const button = $buttons[i];
          button.setAttribute("style","border:1px solid white;margin:0 10px 0 10px;" +
            "padding:0 4px 0 4px;border-radius:5px;");
        }
      },10);
    }

    function changeTree(){
      if(showOverlay.value){
        message.warn('请退出引导状态再进行操作！');
        return false;
      }
      showTree.value = false;
      colspan.value = 6;
    }

    function changeQuery(curVal:boolean){
      if(showOverlay.value){
        message.warn('请退出引导状态再进行操作！');
        return false;
      }
      showQuery.value = curVal;
    }

    const replaceFields = {
      children: 'children',
      title: 'label',
      key: 'value',
    };
    const fileOptions = reactive({
      docKey: '',
      businessType: [] as any[],
      selectBusinessType: [] as any[]
    })
    const wellPurposeTree = ref([]);

    get('wellInfo/getWellPurposeTree', {}).then(data => {
      wellPurposeTree.value = data;
    });

    const wellTypeTree = ref([]);
    get('wellInfo/getWellTypeTree', {}).then(data => {
      wellTypeTree.value = data;
    });

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

    const downFile = (record: any) => {
      download(record.storage_path, record.file_name);
    };
    const resetFields = function () {
      let keys: string[] = Object.keys(formState);
      keys.forEach(key => {
        if (typeof (formState[key]) == "string") {
          formState[key] = '';
        } else if (typeof (formState[key]) == "object") {
          formState[key] = [];
        }
      })
    }

    filterColumns.value = [...columns];

    function showColumnTypeChange() {
      const filterValue = columns.filter((item: any) => {
        if (!showColumnType.value.includes("oil")) {
          if (["oil_prod_mon", "oil_prod_year", "oil"].includes(item.dataIndex)) {
            return false
          }
        }
        if (!showColumnType.value.includes("gas")) {
          if (["gas_prod_mon", "gas_prod_year", "gas"].includes(item.dataIndex)) {
            return false
          }
        }
        if (!showColumnType.value.includes("water")) {
          if (["water_prod_mon", "water_prod_year", "water"].includes(item.dataIndex)) {
            return false
          }
        }
        return true
      })
      //拖拽后在显示隐藏列则需要按拖拽后的列排序
      const sortedArray = filterValue.sort((a, b) => {
        const indexA = filterColumns.value.findIndex(f => f.key == a.key);
        const indexB = filterColumns.value.findIndex(f => f.key == b.key);
        return (indexA == -1 || indexB == -1) ? 1 : indexA - indexB;
      });
      filterColumns.value = [...sortedArray];
      setSettingColumns();
    }

    function getSettingColumns() {
      let userColumnsJson = localStorage.getItem('userColumns');
      let userShowColumnsType = localStorage.getItem('userShowColumnsType');
      if (userColumnsJson != undefined) {
        let array = new Array();
        let userColumns = JSON.parse(userColumnsJson);
        userColumns.forEach(it => {
          array.push(columns.find(c => c.key == it.key));
        })
        filterColumns.value = array;
      }
      if (userShowColumnsType != undefined) {
        showColumnType.value = JSON.parse(userShowColumnsType);
      }
    }

    function setSettingColumns() {
      localStorage.setItem("userShowColumnsType", JSON.stringify(showColumnType.value));
      localStorage.setItem("userColumns", JSON.stringify(filterColumns.value));
    }

    const preCheckValues = ref(Object.assign(showColumnType.value));
    const onCheckboxChange = (checkValues: []) => {
      showColumnTypeChange();
      setTimeout(() => {
        let tbody = document.getElementsByClassName("ant-table-body")[0];
        if (tbody) {
          tbody.scrollLeft = preCheckValues.value.length > checkValues.length ? 0 : tbody.scrollWidth;
        }
        preCheckValues.value = checkValues;
      }, 300)
    }

    const onSelectChange = (keys: any) => {
      selectedRowKeys.value = keys;
    };
    const pagination = computed(() => ({
      total: formState.total,
      current: formState.page,
      pageSize: formState.rows,
      showSizeChanger: true,
      pageSizeOptions: viewModel.value == "list" ? ['10', '20', '30', '40', '50'] : ['12', '24', '36', '48', '60'],
      showTotal: total => getPaginationTotalTitle(total)
    }));

    watch(() => viewModel.value,
      () => {
        pagination.value.current = 1;
        formState.page = 1;
        if (viewModel.value == "list") {
          formState.rows = 10;
          pagination.value.pageSize = 10;
        } else {
          formState.rows = 12;
          pagination.value.pageSize = 12;
        }
        loadData();
      });

    const loadData = async function () {
      loading.value = true;
      const result: any = await postData('wellInfo/getList', formState);

      data.value = result.list;
      formState.total = result.total;
      loading.value = false;
    }
    const handleTableChange: TableProps['onChange'] = (
      pag: { pageSize: number; current: number },
    ) => {
      formState.page = pag.current;
      formState.rows = pag.pageSize;
      loadData();
    };
    const onRangeChange = (dateString, begin, end) => {
      formState[begin] = dateString ? dateString[0].format("YYYY-MM-DD") : '';
      formState[end] = dateString ? dateString[1].format("YYYY-MM-DD") : '';
    };
    const tabChange = (key) => {
      console.log("tabChange", key);
      formState.org_id_a1 = '';
      formState.project_id = '';
      formState.orgList = [];
      formState.unitList = [];
      if (key == "2") {
        subjectTrees.value.data = Object.assign(subjectTrees.value.constructUnitTree);
      } else {
        subjectTrees.value.data = Object.assign(subjectTrees.value.organizationTree);
      }
      data.value=[];
      getSubjectTree();
    }
    const detail = (well_id) => {
      tabsViewStore.addTabByPath('/wellinfo/detail', {id: well_id});
    }
    const onQuery = () => {
      loadData();
      chartMapRef.value.getDatas(formState);
    }
    const treeRef = ref();
    const subjectTrees = ref({
      data: [],
      organizationTree: [],
      constructUnitTree: [],
      expandedKeys: [''],
      selectedKeys: [''],
      autoExpandParent: true,
      searchStr: ''
    });
    const getSubjectData = async function () {
      get('wellInfo/getOrganizationTree', {tabName: subjectTrees.value.searchStr}).then(data => {
        subjectTrees.value.organizationTree = data;
        subjectTrees.value.data = Object.assign(data);
        getSubjectTree();
      });
      get('wellInfo/getConstructUnitTree', {tabName: subjectTrees.value.searchStr}).then(data => {
        subjectTrees.value.constructUnitTree = data;
      });
    }
    const getSubjectTree = async function () {
      //计算第一个展开节点
      subjectTrees.value.expandedKeys = [];
      if (subjectTrees.value.data && subjectTrees.value.data.length > 0) {
        subjectTrees.value.expandedKeys.push((subjectTrees.value.data[0] as any).value + "");
      }
      generateList(subjectTrees.value.data);
    }
    getSubjectData();

    const searchTree = () => {
      if (subjectTrees.value.searchStr == "") {
        return;
      }
      const expanded = dataList
        .map((item: any) => {
          if (item.label != null && item.label.indexOf(subjectTrees.value.searchStr) > -1) {
            return getParentKey(item.value as string, subjectTrees.value.data);
          }
          return null;
        })
        .filter((item, i, self) => item && self.indexOf(item) === i);

      if (expanded.length == 0) {
        message.warning('没有查询到相关目录');
      }
      subjectTrees.value.expandedKeys = expanded as string[];
      subjectTrees.value.autoExpandParent = true;
      // (treeRef.value as any).scrollTo({key:expanded[0]});
    }
    const dataList: any[] = [];
    const generateList = (data: any[]) => {
      for (let i = 0; i < data.length; i++) {
        const node = data[i];
        const label = node.label;
        dataList.push({value: node.value, label: label as string});
        if (node.children) {
          generateList(node.children);
        }
      }
    };

    const getParentKey = (key: string, tree: any[]): string | number | undefined => {
      let parentKey;
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.children) {
          if (node.children.some(item => item.value === key)) {
            parentKey = node.value;
          } else if (getParentKey(key, node.children)) {
            parentKey = getParentKey(key, node.children);
          }
        }
      }
      return parentKey;
    };

    const treeOnExpand = function (keys: string[]) {
      subjectTrees.value.expandedKeys = keys;
      subjectTrees.value.autoExpandParent = false;
    }
    const treeOnSelect = function (selected, selectedNodes, node) {
      console.log(selected, selectedNodes, node);
      if (selectedNodes.node.parent != undefined || activeTab.value == "1") {
        if (activeTab.value == "1") {
          formState.org_id_a1 = selected.length > 0 ? selectedNodes.node.key : '';
          formState.orgList = selected.length > 0 ? [formState.org_id_a1] : [];
          onOrgTreeChange();
        } else {
          formState.project_id = selected.length > 0 ? selectedNodes.node.key : '';
          formState.unitList = selected.length > 0 ? [formState.project_id] : [];
          onUnitTreeChange();
        }
        loadData();
      }
    }
    const orgUnitList: any = ref([]);
    const unitOrgList: any = ref([]);
    let filterTreeData: any[] = [];

    //组织机构和地质单元联动，选择组织机构只显示该组织机构的地质单元
    function filterOrgTree(treeData: any[]) {
      if (formState.unitList.length == 0) {
        return treeData;
      }
      filterTreeData = [];
      treeData.forEach(node => {
        if (unitOrgList.value.indexOf(node.value) > -1) {
          filterTreeData.push(node);
          return;
        }
        eachOrgTreeNode(node.children);
      })
      return filterTreeData;
    }

    function eachOrgTreeNode(treeData: any[]) {
      if (treeData == undefined) {
        return;
      }
      treeData.forEach(node => {
        if (unitOrgList.value.indexOf(node.value) > -1) {
          filterTreeData.push(node);
          return;
        }
        eachOrgTreeNode(node.children);
      })
    }

    function onOrgTreeChange() {
      postData('wellInfo/getOrgProjectList', {orgList: formState.orgList}).then((data: any[]) => {
        orgUnitList.value = data.map(x => x.project_id);
      })
    }

    function onUnitTreeChange() {
      postData('wellInfo/getOrgProjectList', {unitList: formState.unitList}).then((data: any[]) => {
        unitOrgList.value = data.map(x => x.org_id);
      })
    }

    function filterUnitTree(treeData: any[]) {
      if (formState.orgList.length == 0) {
        return treeData;
      }
      filterTreeData = [];
      treeData.forEach(node => {
        if (orgUnitList.value.indexOf(node.value) > -1) {
          filterTreeData.push(node);
          return;
        }
        eachUnitTreeNode(node.children);
      })
      return filterTreeData;
    }

    function eachUnitTreeNode(treeData: any[]) {
      if (treeData == undefined) {
        return;
      }
      treeData.forEach(node => {
        if (orgUnitList.value.indexOf(node.value) > -1) {
          filterTreeData.push(node);
          return;
        }
        eachUnitTreeNode(node.children);
      })
    }

    const showDoc = (id) => {
      get('wellInfo/getWellDocumentList', {wellId: id}).then((data: any[]) => {
        let applyFileList = getStoreFiles();
        data.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;
          }
        })
        docList.value = data;
        isShowDoc.value = true;
        fileOptions.businessType = docList.value.map(x => x.file_business_type);
        fileOptions.businessType = Array.from(new Set(fileOptions.businessType));
      })
    };

    const onAddCart = (file) => {
      let applyFileList = getStoreFiles();
      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 getStoreFiles = () => {
      let applyFileList = new Array();
      let storeList = localStorage.getItem("applyFileList");
      if (storeList != null) {
        applyFileList = JSON.parse(storeList);
      }
      return applyFileList;
    }

    const labelCol = {style: {width: '100px'}};

    const showHelp = () => {
      if (curTour.value && curTour.value['wellInfoTour'] ) {
        (curTour.value['wellInfoTour'] as any).start();
        loadStyle();
        showOverlay.value = true;
      }
    }

    return {
      route,
      selectedRowKeys,
      loading,
      activeTab,
      showTree,
      onSelectChange,
      data,
      expand,
      onQuery,
      loadData,
      onRangeChange,
      chartMapRef,
      showQuery,
      wellTypeList,
      wellPurposeList,
      replaceFields,
      formRef,
      viewModel,
      handleTableChange,
      detail,
      formState,
      isShowDoc,
      showDoc,
      docKey,
      docList,
      resetFields,
      showColumnType,
      filterColumns,
      filterUnitTree,
      filterOrgTree,
      labelCol,
      getTdColor,
      downFile,
      tabChange,
      onCheckboxChange,
      treeRef,
      colspan,
      treeOnExpand,
      subjectTrees,
      fileOptions,
      onBusTypeChange,
      onOrgTreeChange,
      onUnitTreeChange,
      getSubjectTree,
      searchTree,
      treeOnSelect,
      pagination,
      getSettingColumns,
      wellPurposeTree,
      wellTypeTree,
      numberToCurrencyNo,
      onAddCart,
      handleResizeColumn: (w, col) => {
        col.width = w;
      },
      curStepVal,steps,myOptions,curTour,showOverlay,myCallbacks,loadStyle,changeTree,changeQuery,showHelp
    };

  },
  mounted(){
    this.curTour = getCurrentInstance()?.appContext.config.globalProperties.$tours;
    console.log("tour2",this.curTour);
    if(this.curTour && this.curTour['wellInfoTour']){
      const localData = localStorage.getItem('wellInfoTourShow');
      const curTour = localData?JSON.parse(localData):null;
      if(curTour==null||!curTour.ifShowed){
        this.showOverlay = true;
        (this.curTour['wellInfoTour'] as any).start();
        const curLocalData = JSON.stringify({ifShowed:true});
        localStorage.setItem('wellInfoTourShow',curLocalData);
      }
    }

  },
  beforeMount() {
    this.loadStyle();
  },
  created() {
    this.getSettingColumns();
    //this.loadData();
  },
  activated() {
  }
});
</script>
<style lang="less">
.tipsTitle{
  color: white;
  background: #4c8dff;
  font-size: 15px;
  border-radius:10px 10px 0 0;
  padding:5px 20px 0 10px;
  font-weight:bolder;
  display: inline-block;
  width:400px;
}
.tipsContent{
  color: white;
  background: #4c8dff;
  font-size: 14px;
  padding-left: 20px;
}

.leftTriangle{
  height: 0;
  border-top: 12px solid transparent;
  border-bottom: 15px solid transparent;
  border-left: 15px solid transparent;
  border-right: 12px solid #4c8dff;
}

.rightTriangle{
  height: 0;
  border-top: 12px solid transparent;
  border-bottom: 15px solid transparent;
  border-left: 15px solid #4c8dff;
  border-right: 12px solid transparent;
}

.topTriangle{
  height: 0;
  border-top: 18px solid transparent;
  border-bottom: 18px solid #4c8dff;
  border-left: 15px solid transparent;
  border-right: 15px solid transparent;
}


.bottomTriangle{
  height: 0;
  border-top: 18px solid #4c8dff;
  border-bottom: 18px solid transparent;
  border-left: 15px solid transparent;
  border-right: 15px solid transparent;
}

.query-index {
  display: flex;
  flex-direction: row;
  height: 100%;
  background-color: white;
  overflow: hidden;
  position: relative;
}

.apply-cart {
  position: fixed;
  right: 10px;
  bottom: 80px;
  width: 55px;
  z-index: 99;
  cursor: pointer;
}

.query-index-tree {
  min-width: 260px;
  max-width: 360px;
  border-right: 2px solid #f2f2f2;
  margin-right: 5px;
}

.query-index-close {
  width: 15px;
  padding-top: 10px;
  padding-left: 10px;
}

.query-index-content {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  width: 80%;
}

.query-index-row {
  height: 34px;
}

.query-index-form {
  padding: 15px 10px 10px 15px;
}

.query-index-table {
  flex-grow: 1;
  display: flex;

  .ant-row {
    width: 100%;
  }
}

.query-index-tabs {
  margin-left: 10px;
  margin-right: 10px;
  height: 100%;
  flex: 1;
}

.tabs-view-content {
  padding: 0px;
}

.query-index-tree-item {
  white-space: nowrap; /*强制span不换行*/
  display: inline-block; /*将span当做块级元素对待*/
  text-overflow: ellipsis; /*超出部分以点号代替*/
}

.query-index-tree-search {
  padding: 5px;
  border-bottom: 2px solid #f2f2f2;
  display: flex;
  align-items: center;
}

.query-index-tree-box {
  padding: 5px;
  padding-top: 10px;
  overflow-y: scroll;
  height: 100%;
}

.col-text {
  padding-right: 0px !important;
  text-align: right;
  font-weight: bold;
}

.col-content {
  width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.ant-card-body {
  padding: 10px;
}

.well-card-table {
  width: 100%;

  th {
    width: 25%;
    text-align: left;
    font-size: 12px;
  }

  td {
    width: 25%;
    text-align: left;
    font-size: 12px;
  }
}

.ant-card-index {

  .ant-card-head-title {
    font-weight: bold;
    color: #1f37dd;
  }

  .ant-card-head {
    padding: 0px 10px;
    height: 35px;
    background-color: #F9FCFF;
  }

  .ant-card-head-wrapper {
    height: 35px;
    margin-top: 5px;
  }
}

.ant-card-index:hover {
  box-shadow: 3px 2px 10px #999;
  opacity: 0.8;
}

.color_level1, .ant-table-tbody > tr > td.color_level1:hover {
}

.color_level2, .ant-table-tbody > tr > td.color_level2:hover {
  background-color: #EAF4FF !important;
}

.color_level3, .ant-table-tbody > tr > td.color_level3:hover {
  background-color: #D5EAFF !important;
}

.color_level4, .ant-table-tbody > tr > td.color_level4:hover {
  background-color: #B7DBFF !important;
}

.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;
  }
}
</style>

