<template>
  <div>
    <a-card :bordered="false">
      <a-form
        :label-col="{ xl: 7, lg: 5, md: 7, sm: 4 }"
        :wrapper-col="{ xl: 17, lg: 19, md: 17, sm: 20 }"
      >
        <a-row :gutter="8">
          <a-col
            :xl="6"
            :lg="12"
            :md="12"
            :sm="24"
            :xs="24"
          >
            <a-form-item label="区域名称">
              <a-input
                v-model:value.trim="queryform.regionName"
                placeholder="请输入区域名称"
                allow-clear
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col
            :xl="6"
            :lg="12"
            :md="12"
            :sm="24"
            :xs="24"
          >
            <a-form-item label="区域简称">
              <a-input
                v-model:value.trim="queryform.simpleName"
                placeholder="请输入区域简称"
                allow-clear
              ></a-input>
            </a-form-item>
          </a-col>
          <a-col
            :xl="6"
            :lg="12"
            :md="12"
            :sm="24"
            :xs="24"
          >
            <a-form-item label="运营状态">
              <a-select
                v-model:value="queryform.inOperation"
                placeholder="请选择运营状态"
                allow-clear
              >
                <a-select-option value="">全部</a-select-option>
                <a-select-option value="1">正常</a-select-option>
                <a-select-option value="0">停运</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col
            :xl="6"
            :lg="12"
            :md="12"
            :sm="24"
            :xs="24"
          >
            <a-form-item
              class="ele-text-right"
              :wrapper-col="{ span: 24 }"
            >
              <a-space>
                <a-button
                  type="primary"
                  style="background-color: #5cc750"
                  @click="search"
                >查询</a-button>
                <!-- <a-button>重置</a-button> -->
              </a-space>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <!-- 数据操作 -->
      <a-space style="margin-bottom: 10px">
        <a-button
          style="background-color: #5cc750"
          type="primary"
          class="ele-btn-icon"
          @click="handleAdd"
        >
          <template #icon>
            <plus-outlined />
          </template>
          <span>新增</span>
        </a-button>
      </a-space>
      <!-- 表格 -->
      <a-table
        :pagination="pagination"
        @change="handleTableChange"
        bordered
        :columns="columns"
        :dataSource="dataSource"
        :scroll="{ x: 'max-content' }"
      >
        <template #headerCell="{ column }">
          <template v-if="column.key === 'action'">
            <SettingOutlined style="margin-right: 5px" />{{ column.title }}
          </template>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'inOperation'">
            <a-tag
              v-if="record.inOperation == '0'"
              color="#f50"
            >停运</a-tag>
            <a-tag
              v-if="record.inOperation == '1'"
              color="#87d068"
            >正常</a-tag>
          </template>
          <template v-if="column.key === 'simpleName'">
            <span>{{record.simpleName}}</span><a
              style="margin-left: 5px;"
              @click="openEditSimpleName(record)"
            >编辑</a>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a>详情</a>
              <a-divider type="vertical" />
              <a>地图</a>
              <a-divider type="vertical" />
              <a-dropdown>
                <a
                  class="ant-dropdown-link"
                  @click="e => e.preventDefault()"
                >编辑
                  <DownOutlined />
                </a>
                <template v-slot:overlay>
                  <a-menu>
                    <a-menu-item>
                      <a @click="feeConfigInfo(record)">费用信息</a>
                    </a-menu-item>
                    <a-menu-item>
                      <a @click="regionConfigInfo(record)">运营配置</a>
                    </a-menu-item>
                    <a-menu-item>
                      <a @click="handleOtherAction(record)">运维配置</a>
                    </a-menu-item>
                    <a-menu-item>
                      <a @click="handleEdit(record)">调度配置</a>
                    </a-menu-item>
                    <a-menu-item>
                      <a @click="handleSettings(record)">换电配置</a>
                    </a-menu-item>
                    <a-menu-item>
                      <a @click="handleEditORMap(record)">修改地图</a>
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
              <a-divider type="vertical" />
              <a-dropdown>
                <a
                  class="ant-dropdown-link"
                  @click="e => e.preventDefault()"
                >账号
                  <DownOutlined />
                </a>
                <template v-slot:overlay>
                  <a-menu>
                    <a-menu-item>
                      <a @click="addAccount(record)">新增账号</a>
                    </a-menu-item>
                    <a-menu-item>
                      <a @click="accountList(record)">账号列表</a>
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
    <!-- 费用配置 -->
    <a-modal
      v-model:open="open"
      :title="openTitle"
      @ok="handleOkFeeModal"
      width="1000px"
      :maskClosable="false"
    >
      <RegionFeeCofFrom
        :key="modalFreeKey"
        ref="formModel"
      ></RegionFeeCofFrom>
    </a-modal>
    <!-- 运营配置 -->
    <a-modal
      v-model:open="openConfig"
      :title="openTitleConfig"
      @ok="handleOkConfgModal"
      width="1000px"
      :maskClosable="false"
    >
      <OperateConfForm
        :key="modalOperateKey"
        ref="formModelConfig"
      ></OperateConfForm>
    </a-modal>
    <!-- 地图 -->
    <operateRegionMap
      ref="editORMapModel"
      :onCallBack="onORMapCallBack"
      :openTitle="openORMapTitle"
    ></operateRegionMap>
    <!-- 编辑区域简称 -->
    <a-modal
      v-model:open="openSimpleName"
      title="编辑区域简称"
      @ok="handleOkEditSimpleName"
      width="500px"
      :maskClosable="false"
    >
      <a-form
        :label-col="{ xl: 7, lg: 5, md: 7, sm: 4 }"
        :wrapper-col="{ xl: 17, lg: 19, md: 17, sm: 20 }"
      >
        <a-form-item label="区域简称">
          <a-input
            v-model:value.trim="editRecord.simpleName"
            placeholder="请输入区域简称"
            allow-clear
          ></a-input>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, nextTick } from 'vue'
import { callOperate } from '@/apis/call.js'
import { message } from 'ant-design-vue'
import config from '@/utils/config.js'
import RegionFeeCofFrom from '@/views/form/operateregion/RegionFeeCofFrom.vue'
import OperateConfForm from '@/views/form/operateregion/OperateConfForm.vue'
import operateRegionMap from '../OperateRegionMap/index.vue'
import {
  SettingOutlined
} from '@ant-design/icons-vue'
import { useRouter, useRoute } from 'vue-router'
import { getGUID } from '@/utils/tools'
import _ from 'lodash'

// 表格行数据
const dataSource = ref([])
const data = ref([])
const formModel = ref(null);
const formModelConfig = ref(null);
const openTitle = ref('');
const openTitleConfig = ref('');
const editRecord = ref({});
const router = useRouter()
const open = ref(false);
const openConfig = ref(false);
const openSimpleName = ref(false);
const editORMapModel = ref(null);
const openORMapTitle = ref('地图');
const modalFreeKey = ref(getGUID())
const modalOperateKey = ref(getGUID())

// 查询相关
const queryform = ref({
  regionName: '',
  simpleName: '',
  inOperation: '',
  pageParam: {
    pageNum: config.pageParam.pageNum,
    pageSize: config.pageParam.pageSize
  }
})

//对于每页数据的管理
let pagination = reactive({
  total: dataSource.value.length,
  current: queryform.value.pageParam.pageNum,
  pageSize: queryform.value.pageParam.pageSize,
  showSizeChanger: true,
  pageSizeOptions: config.pageParam.pageSizeOptions,
  showQuickJumper: true
})

// 表格列配置
const columns = ref([
  {
    title: '序号',
    key: 'index',
    width: 80,
    align: 'center',
    dataIndex: 'index'
  },
  {
    key: 'zoneName',
    title: '所属行政区',
    width: 200,
    align: 'center',
    dataIndex: 'zoneName'
  },
  {
    key: 'operationRegionName',
    title: '区域名称',
    width: 150,
    align: 'center',
    dataIndex: 'operationRegionName'
  },
  {
    key: 'simpleName',
    title: '区域简称',
    width: 150,
    align: 'center',
    dataIndex: 'simpleName'
  },
  {
    key: 'inOperation',
    title: '运营状态',
    width: 150,
    align: 'center',
    dataIndex: 'inOperation'
  },
  {
    key: 'regionRank',
    title: '区域级别',
    width: 150,
    align: 'center',
    dataIndex: 'regionRank'
  },
  {
    key: 'regionCode',
    title: '区域编码',
    width: 150,
    align: 'center',
    dataIndex: 'regionCode'
  },
  {
    key: 'siteCount',
    title: '站点数量',
    width: 150,
    align: 'center',
    dataIndex: 'siteCount'
  },
  {
    key: 'freeDuration',
    title: '免费时长',
    width: 150,
    align: 'center',
    dataIndex: 'freeDuration'
  },
  {
    key: 'billingStandard',
    title: '计费标准',
    width: 200,
    align: 'center',
    dataIndex: 'billingStandard'
  },
  {
    key: 'dispatchFee',
    title: '运调度费(元)',
    width: 250,
    align: 'center',
    dataIndex: 'dispatchFee'
  },
  {
    key: 'cappedAmount',
    title: '封顶金额(元)',
    width: 150,
    align: 'center',
    dataIndex: 'cappedAmount'
  },
  {
    key: 'createdAt',
    title: '创建时间',
    width: 150,
    align: 'center',
    dataIndex: 'createdAt'
  },
  {
    title: '操作',
    key: 'action',
    width: 300,
    align: 'center',
    fixed: 'right',
  }
])

//获取用户列表数据并格式化字段
onMounted(async () => {
  getData();
})

const getData = async () => {
  let url = "/ebikeRegion/pageOperation?pageNum=" + queryform.value.pageParam.pageNum + "&pageSize=" + queryform.value.pageParam.pageSize
  if (queryform.value.regionName) {
    url += "&regionName=" + queryform.value.regionName
  }
  if (queryform.value.simpleName) {
    url += "&simpleName=" + queryform.value.simpleName
  }
  if (queryform.value.inOperation) {
    url += "&inOperation=" + queryform.value.inOperation
  }
  const res = await callOperate(url, {}, "get");
  if (res.code != 200) {
    message.error(res.message)
    return
  }
  data.value = res.data.records
  data.value = data.value.map((item, index) => {
    index++
    return { ...item, index }
  })
  dataSource.value = data.value
  pagination.total = res.data.totalRow
}


// 对每页数据显示的交互
let handleTableChange = (pagina) => {
  pagination.current = pagina.current
  pagination.pageSize = pagina.pageSize
  queryform.value.pageParam.pageNum = pagina.current
  queryform.value.pageParam.pageSize = pagina.pageSize
  getData()
}

const search = () => {
  getData()
}

const openEditSimpleName = (record) => {
  openSimpleName.value = true;
  editRecord.value = _.cloneDeep(record)
}

const handleOkEditSimpleName = () => {
  callOperate("/ebikeRegion/updateOperation", editRecord.value).then((res) => {
    if (res.code != 200) {
      message.error(res.message)
      return
    }
    if (res.code == 200) {
      openSimpleName.value = false;
      getData()
    }
  })
}

/**
 * 编辑费用配置
 * @param record 
 */
const feeConfigInfo = (record) => {
  modalFreeKey.value = getGUID();
  openTitle.value = "费用信息 - " + record['operationRegionName']
  open.value = true
  nextTick(() => {
    if (formModel.value) {
      formModel.value.openForm({ operationRegionId: record['operationRegionId'] });
    } else {
      console.log('formModel is not ready yet');
    }
  });
}

/**
 * 费用配置modal确定
 */
const handleOkFeeModal = () => {
  formModel.value.formSave((data => {
    open.value = false;
    if (data['code'] == 200) {
      getData()
    } else {
      message.error(data.message)
    }
  }));
}

/**
 * 编辑运营配置
 * @param record 
 */
const regionConfigInfo = (record) => {
  modalOperateKey.value = getGUID();
  openTitleConfig.value = "运营配置 - " + record['operationRegionName']
  openConfig.value = true
  nextTick(() => {
    if (formModelConfig) {
      formModelConfig.value.openForm({ operationRegionId: record['operationRegionId'] });
    } else {
      console.log('formModel is not ready yet');
    }
  });
}

/**
 * 运营配置modal确定
 */
const handleOkConfgModal = () => {
  formModelConfig.value.formSave((data => {
    openConfig.value = false;
    if (data['code'] == 200) {
      getData()
    } else {
      message.error(data.message)
    }
  }));
}

const handleEditORMap = (record) => {
  openORMapTitle.value = '绘制地图（' + record['operationRegionName'] + '）';
  const data = {
    operationRegionId: record['operationRegionId']
  }
  editORMapModel.value.showModal(data);
}

const onORMapCallBack = () => {

}

const handleAdd = () => {
  router.push('/Urban/OperateRegionAdd');
}

</script>
