<template>
  <div class="examine-container">
    <div class="left-container">
      <template v-for="source in sourceTypes" :key="source.SERVICETYPE">
        <div class="soure-item-row" :class="{ active: current === source.SERVICETYPE }" @click="selectHandle(source)">
          {{ source.name }}
        </div>
      </template>
    </div>
    <div class="right-container">
      <BasicTable @register="registerTable" @fetch-success="onFetchSuccess">
        <template #toolbar>
          <Authority>
            <a-button type="primary" @click="showModalBatch">IP管理</a-button>
          </Authority>
        </template>

        <template #action="{ record }">
          <TableAction :actions="[
            {
              label: 'IP管理',
              onClick: showModal.bind(null, record),
            },
            // {
            //   label: '删除',
            //   onClick: handleDel.bind(null, record),
            // },
          ]" />
        </template>
      </BasicTable>
    </div>
    <a-modal v-model:visible="visible" :label-col="labelCol" :wrapper-col="wrapperCol" width="433px" title="IP管理"
      @ok="handleOk">
      <div class="wapper">
        <!-- <p><span>IP地址:&nbsp;</span><a-input v-model:value="formState.ipaddress" /></p> -->
        <div class="tableIp">
          <tr>
            <th>序号</th>
            <th>IP地址</th>
            <th>操作</th>
          </tr>
          <tr v-for="(i, index) in formState.ipaddressList" :key="index">
            <td>{{ index + 1 }}</td>
            <td v-if="(index + 1) == formState.ipaddressList.length"><input type="text"
                v-model="formState.ipaddressList[index]"></td>
            <td v-else>{{ i }}</td>
            <td>
              <img src="/@/assets/images/sc.png" alt="" srcset="" @click="remove(index)">
              <img v-if="(index + 1) == formState.ipaddressList.length" @click="add(index)" src="/@/assets/images/add.png"
                alt="" srcset="">
            </td>
          </tr>
        </div>

      </div>
      <span style="clear: both;"></span>
    </a-modal>
  </div>
</template>
<script lang="ts">
import { defineComponent, nextTick, ref, watch } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { delRole, setRoleStatus } from '/@/api/system/system';
import {
  columns,
  searchFormSchemaMR,
  searchFormSchemaER,
  searchFormSchemaDR,
  searchFormSchemaSR,
} from './map.data';
import { RoleEnum } from '/@/enums/roleEnum';
import { Authority } from '/@/components/Authority';
import { useBatchDelete } from '/@/hooks/web/useBatchDelete';
import { Switch, Popconfirm, message } from 'ant-design-vue';
import Moment from 'moment';
import { getProxyList, proxySave, proxyDel } from '/@/api/resource/proxy';
import { useModal } from '/@/components/Modal';
import { useRouter } from 'vue-router';
import { useAppStore } from '/@/store/modules/app';

export default defineComponent({
  name: 'RoleManagement',
  components: {
    BasicTable,
    TableAction,
    Authority,
    Switch,
    Popconfirm
  },
  setup() {
    const appStore = useAppStore();
    const { currentRoute } = useRouter();
    const currRoute = currentRoute.value;
    let current = ref(currRoute?.query?.type || 'MR');
    let statusShow = ref(1);
    const [registerTable, { getSelectRows, setProps, reload, setSelectedRowKeys, getDataSource, getSelectRowKeys }] = useTable({
      title: '地图资源审核列表',
      api: (param) => {
        statusShow.value = param.checkStatus;
        const data = Object.assign(param, { serviceType: current.value });
        return getProxyList(data);
      }, //求接口
      //dataSource: dataSources, //表格的数据
      columns,
      // rowKey: (record) => record.SERVICEID,
      rowKey: 'id',
      formConfig: {
        labelWidth: 90,
        schemas: searchFormSchemaMR,
      },
      useSearchForm: true,
      showTableSetting: true,
      bordered: true,
      showIndexColumn: true,
      actionColumn: {
        width: 200,
        title: '操作',
        dataIndex: 'action',
        slots: { customRender: 'action' },
        fixed: 'right',
      },
      pagination: {
        hideOnSinglePage: false,
        // pageSize: 10,
      },
      clickToRowSelect: true, //点击当前行多选框不选中,默认是true
      rowSelection: { type: 'checkbox' }, //是否有多选功能
      tableSetting: {
        redo: true,
        size: true,
        setting: false,
        fullScreen: false,
      },
    });

    const onFetchSuccess = () => {
      // 请求后拿到数据，打开对应的资源审核弹窗
      nextTick(() => {
        let dataList = getDataSource()
        if (currRoute?.query?.bussid && appStore.routerPushAuditFlag) {
          dataList.forEach(item => {
            item.BUSSID === currRoute.query.bussid && handleEdit(item)
          })
          let searchFormSchema = searchFormSchemaMR;
          let title = '地图资源审核列表';
          if (current.value === 'MR') {
            searchFormSchema = searchFormSchemaMR;
            title = '地图资源审核列表';
          } else if (current.value === 'ER') {
            searchFormSchema = searchFormSchemaER;
            title = '场景资源审核列表';
          } else if (current.value === 'DR') {
            searchFormSchema = searchFormSchemaDR;
            title = '文件资源审核列表';
          } else {
            searchFormSchema = searchFormSchemaSR;
            title = '组件资源审核列表';
          }
          setProps({
            title: title,
            formConfig: {
              labelWidth: 90,
              schemas: searchFormSchema,
            },
          });
        }
      });
    }

    const moment = Moment;
    const ischect = ref(true)
    const sourceTypes = ref([
      { SERVICETYPE: 'MR', name: '地图资源' },
      { SERVICETYPE: 'ER', name: '场景资源' },
      { SERVICETYPE: 'DR', name: '文件资源' },
      { SERVICETYPE: 'SR', name: '组件资源' },
    ]);
    const { hasBatchDelete, handleDeleteOrBatchDelete, selectionOptions, resetSelectedRowKeys } =
      useBatchDelete(delRole, handleSuccess, setProps);
    selectionOptions.rowSelection.getCheckboxProps = (record: Recordable) => {
      // Demo:status为1的选择框禁用
      // if (record.status === 1) {
      //   return { disabled: true };
      // } else {
      //   return { disabled: false };
      // }
    };
    const [registerModal, { openModal }] = useModal();
    watch(
      () => current.value, (val) => {
        let searchFormSchema = searchFormSchemaMR;
        let title = '地图资源审核列表';
        if (val === 'MR') {
          searchFormSchema = searchFormSchemaMR;
          title = '地图资源审核列表';
        } else if (val === 'ER') {
          searchFormSchema = searchFormSchemaER;
          title = '场景资源审核列表';
        } else if (val === 'DR') {
          searchFormSchema = searchFormSchemaDR;
          title = '文件资源审核列表';
        } else {
          searchFormSchema = searchFormSchemaSR;
          title = '组件资源审核列表';
        }
        setProps({
          title: title,
          formConfig: {
            labelWidth: 90,
            schemas: searchFormSchema,
          },
        });
        reload();
      }
    );
    nextTick(() => {
      setProps(selectionOptions);
    });

    function selectHandle(record) {
      current.value = record.SERVICETYPE;
    }

    /**
     * 详情
     */
    async function handleDel(record: Recordable) {
      console.log(record);
      record.serviceid = record.SERVICEID;
      record.ipaddress = record.IPS
      proxyDel({
        serviceid: record.SERVICEID,
        serviceType: record.SERVICETYPE,
        ipaddress: record.IPS
      }).then((r) => {
        if (r) {
          message.success(r.resp_msg);
          reload();
        } else {
          message.error('删除代理失败！');
        }
      })
    }

    /**
     * 审核
     */
    function handleEdit(record: Recordable) {
      ischect.value = true;
      setTimeout(() => {
        openModal(true, {
          record,
          isUpdate: true,
        });
        appStore.setRouterPushAuditFlag(false)
      }, 100);
    }


    function handleSuccess() {
      openModal(false, {
        isUpdate: false,
      });
      reload();
    }

    const visible = ref(false);

    const disabled = ref(true);
    const showModal = (e) => {
      console.log(e);
      visible.value = true;
      disabled.value = e ? true : false;
      if (e) {
        formState.value.serviceid = e.SERVICEID;
        formState.value.ipaddress = e.IPS;
        formState.value.ipaddressList = e?.IPS?.split(',') || [''];
      }
    };

    function showModalBatch() {
      var list = getSelectRowKeys();
      if (list.length) {
        formState.value.serviceid = list.join(',');
        visible.value = true;
      }
    };

    function handleOk() {
      formState.value.ipaddress = formState.value.ipaddressList.join(',');
      proxySave(formState.value).then((r) => {
        if (r.resp_code == 0) {
          visible.value = false;
          formState.value.ipaddress = '';
          formState.value.serviceid = '';
          message.success('保存成功');
          reload();
          setSelectedRowKeys([]);
        } else {
          message.error(r.resp_msg);
        }
      })
    };
    const formState = ref({
      ipaddress: "",
      serviceid: "",
      ipaddressList: []
    });

    function remove(i) {
      formState.value.ipaddressList.remove(i);
    }

    function add(i) {
      formState.value.ipaddressList.push('');
    }

    return {
      add,
      remove,
      showModalBatch,
      disabled,
      labelCol: { span: 2 },
      wrapperCol: { span: 6 },
      formState,
      visible,
      handleOk,
      showModal,
      statusShow,
      current,
      moment,
      ischect,
      sourceTypes,
      registerTable,
      registerModal,
      handleDel,
      handleEdit,
      handleSuccess,
      RoleEnum,
      hasBatchDelete,
      handleDeleteOrBatchDelete,
      selectHandle,
      onFetchSuccess
    };
  },
});
</script>
<style scoped lang="less">
.tableIp tr img {
  width: 18px;
  height: 18px;
  cursor: pointer;
  float: left;
  margin-right: 6px;
}

.tableIp tr {
  border-bottom: 1px solid #EFF0F5;
  display: block;
}

.tableIp {
  width: 413px;
}

.tableIp th {
  text-align: center;
  height: 40px;
  line-height: 40px;
  background: #F4F4F9;
}

.tableIp td {
  text-align: center;
  height: 40px;
  line-height: 40px;
}

.tableIp input {
  border: solid 1px #E6E6E6;
  text-align: center;
  width: 200px;
}

.tableIp th:first-child,
.tableIp td:first-child {
  width: 50px;
}

.tableIp th:nth-child(2),
.tableIp td:nth-child(2) {
  width: 313px;
}

.tableIp th:last-child,
.tableIp td:last-child {
  width: 50px;
}

.wapper {
  padding: 10px;
  // height: 130px;
}

.wapper p {
  margin-bottom: 10px;
  height: 43px;
}

.wapper p span {
  float: left;
  height: 32px;
  line-height: 32px;
}

.wapper p input {
  float: left;
  width: 430px;
}

.examine-container {
  display: flex;
  height: 100%;
  width: 100%;

  .left-container {
    width: 240px;
    height: calc(100% - 32px);
    margin: 16px 0 16px 10px;
    padding: 10px 20px;
    background-color: #fff;
    border-radius: 2px;

    .soure-item-row {
      height: 34px;
      width: 100%;
      margin: 20px 0;
      line-height: 34px;
      text-align: center;
      font-size: 14px;
      font-weight: normal;
      letter-spacing: 0px;
      color: #333333;
      background: #eff0f5;
      border-radius: 2px;
      cursor: pointer;
    }

    .active {
      background: #0671dd;
      color: #fff;
    }
  }

  .right-container {
    width: calc(100% - 260px);
    height: 100%;
  }
}
</style>

