<template>
  <div>
    <a-form style="margin-bottom: 10px" layout="inline">
      <a-form-item label="供应商名称:">
        <a-input v-model:value="searchText" placeholder="请输入供应商名称" />
      </a-form-item>
      <a-form-item label="是否会员:">
        <a-select
          v-model:value="isVip"
          allowClear
          style="width: 150px"
          placeholder="请选择是否为会员"
        >
          <a-select-option value="1">会员</a-select-option>
          <a-select-option value="0">非会员</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="区域现货:">
        <a-select
          v-model:value="isScOpen"
          allowClear
          style="width: 150px"
          placeholder="请选择是否为区域现货"
        >
          <a-select-option value="1">已开通</a-select-option>
          <a-select-option value="0">未开通</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item>
        <a-button @click="onReSet">重置</a-button>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="onSearch">查询</a-button>
      </a-form-item>
    </a-form>
    <a-table
      :columns="columns"
      :dataSource="list"
      :loading="listloading"
      :pagination="pagination"
      :rowKey="(record) => record.sysid"
      :scroll="{ x: 1350 }"
      bordered
    >
      <template #isScOpen="{ record }">
        {{ record.isScOpen ? '已开通' : '未开通' }}
      </template>
      <template #isVip="{ record }">
        {{ record.isVip ? '会员' : '非会员' }}
      </template>
      <template #hasBankInfo="{ record }">
        <p>{{ record.belongBank }}</p>
        <p>{{ record.payeeAccount }}</p>
        <p>{{ record.payee }}</p>
        <p>{{ record.payeeBank }}</p>
      </template>
      <template #action="{ record }">
        <a-dropdown>
          <template #overlay>
            <a-menu>
              <a-menu-item key="1">
                <UserOutlined />
                <a @click="getContactInfo(record)">查看联系人</a>
              </a-menu-item>
              <a-menu-item key="2">
                <UserOutlined />
                <a @click="showBindingDialog(record)">平台绑定</a>
              </a-menu-item>
              <a-menu-item key="3">
                <UserOutlined />
                <a @click="expansion(record)">数据扩容</a>
              </a-menu-item>
              <a-menu-item key="4">
                <a @click="showregionalSpotVisible(record)">区域现货授权</a>
              </a-menu-item>
            </a-menu>
          </template>
          <a-button type="primary">
            更多
            <!-- <DownOutlined /> -->
            <a-icon type="down" />
          </a-button>
        </a-dropdown>
      </template>
      <template #action1="{ record }">
        <a @click="showOpenGHSDialog(record)">开通</a>
      </template>
    </a-table>
    <a-modal title="联系人信息" v-model:visible="visible" :footer="null">
      <a-table
        :columns="infoColumns"
        :dataSource="infoList"
        :pagination="false"
        :loading="listloading1"
        :rowKey="(record) => record.sysid"
        bordered
      >
        <template #action="{ record }">
          <a @click="showResetPwd(record)">修改密码</a>
        </template>
      </a-table>
    </a-modal>

    <a-modal
      title="开通供货商平台权限"
      v-model:visible="openGHSDialogVisible"
      @cancel="openGHSDialogVisible = false"
      width="700px"
    >
      <div style="margin-bottom: 10px; display: flex; justify-content: space-between">
        <div>
          <a-button
            :loading="batchOpening"
            type="primary"
            @click="batchOpen"
            style="margin-right: 10px"
            >批量开通平台</a-button
          >
          <a-button
            :loading="batchOpening"
            type="primary"
            @click="batchClose"
            style="margin-right: 10px"
            >批量关闭平台</a-button
          >
          <a-button type="primary" @click="showBanDialog('禁用', true)" style="margin-right: 10px"
            >批量禁用平台</a-button
          >
          <a-button type="primary" @click="showBanDialog('解禁', true)">批量解禁平台</a-button>
        </div>
        <a-button type="primary" @click="showRecord">操作记录</a-button>
      </div>
      <a-table
        :columns="openGHSColumns"
        :dataSource="openGHSDialogData"
        :pagination="false"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        :loading="openGHSDialogloading"
        :rowKey="(record) => record.sysid"
        bordered
      >
        <template #status="{ text }">
          {{ text === 1 ? '开通' : '关闭' }}
        </template>
        <template #action="{ record }">
          <a-button v-if="record.isOpen === 1" type="link" @click="closePlat(record)"
            >关闭</a-button
          >
          <a-button v-else type="link" @click="openPlat(record)">开通</a-button>
          <a-button
            v-if="record.isDisable === 1"
            type="link"
            @click="showBanDialog('解禁', false, record)"
            >解禁</a-button
          >
          <a-button v-else type="link" @click="showBanDialog('禁用', false, record)">禁用</a-button>
        </template>
      </a-table>
      <template #footer>
        <a-button @click="openGHSDialogVisible = false">取消</a-button>
      </template>
    </a-modal>
    <a-modal
      title="修改供货商信息"
      v-model:visible="ghsInfoDialogVisible"
      :destroyOnClose="true"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <template #footer>
        <a-button :loading="confirmLoading" @click="handleCancel">取消</a-button>
        <a-button :loading="confirmLoading" type="primary" @click="handleOk">确认</a-button>
      </template>
      <a-form :form="editForm" @submit="handleSubmit">
        <div hidden>
          <a-form-item>
            <a-input
              hidden
              v-decorator="[
                'supplierCode',
                { rules: [{ required: false, message: '请输入供货商名称!' }] },
              ]"
            />
          </a-form-item>
        </div>
        <a-form-item label="供货商名称" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
          <a-input
            v-decorator="[
              'supplierName',
              { rules: [{ required: false, message: '请输入供货商名称!' }] },
            ]"
          />
        </a-form-item>
        <a-form-item label="供货商简称" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
          <a-input
            v-decorator="[
              'supplierShortName',
              { rules: [{ required: false, message: '请输入供货商简称!' }] },
            ]"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <a-modal
      width="50%"
      title="平台绑定"
      v-model:visible="bindingDialog"
      :destroyOnClose="true"
      @ok="bindingDialog = false"
      @cancel="bindingDialog = false"
    >
      <div>
        <a-table
          :columns="columns2"
          :dataSource="bindingList"
          :loading="bindingloading"
          :rowKey="(record) => record.platCode"
          bordered
        >
          <template #action="{ record }">
            <a-button type="link" :disabled="record.platSupplierCode" @click="createAccount(record)"
              >创建帐号</a-button
            >
          </template>
        </a-table>
      </div>
    </a-modal>
    <a-modal
      title="修改密码"
      v-model:visible="resetPwdVisible"
      :destroyOnClose="true"
      @ok="handlePwdOk"
      @cancel="handlePwdCancel"
    >
      <template #footer>
        <a-button :loading="confirmLoading" @click="handlePwdCancel">取消</a-button>
        <a-button :loading="confirmLoading" type="primary" @click="handlePwdOk">确定</a-button>
      </template>
      <a-form
        :model="pwdForm"
        ref="pwdFormRef"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        @submit="handlePwdSubmit"
      >
        <div>
          <a-form-item
            label="帐号"
            prop="username"
            :rules="[{ required: false }]"
            :label-col="{ span: 5 }"
            :wrapper-col="{ span: 12 }"
          >
            <a-input disabled v-model:value="pwdForm.username" />
          </a-form-item>
        </div>
        <a-form-item
          label="密码"
          prop="password"
          :rules="[{ required: true, message: '请输入密码', trigger: 'blur' }]"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 12 }"
        >
          <a-input type="password" v-model:value="pwdForm.password" />
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal
      width="30%"
      title="选择平台"
      v-model:visible="changePlatDialog"
      :destroyOnClose="true"
      :afterClose="changePlatDialogClose"
      :confirmLoading="selestedLoading"
      @ok="submitChangePlat"
      @cancel="changePlatDialog = false"
    >
      <a-select
        mode="multiple"
        :default-value="selestedPlist"
        style="width: 80%; margin-left: 20px"
        placeholder="请选择平台"
        @change="handleChange"
      >
        <a-select-option v-for="item in platList" :key="item.sysid" :value="item.platCode">
          {{ item.platName }}
        </a-select-option>
      </a-select>
    </a-modal>
    <a-modal title="填写备注" v-model:visible="banNoteDialogVisible" @cancel="closeBanNoteDialog">
      <div style="padding: 10px">
        <p style="margin-bottom: 10px"
          >{{ banType }}以下平台：{{
            isBatch ? selectedRows.map((item) => item.platName).join('，') : curPlat.platName
          }}</p
        >
        <a-textarea v-model:value="banNote" placeholder="填写备注" />
      </div>
      <template #footer>
        <a-button :loading="operatingBan" @click="closeBanNoteDialog">取消</a-button>
        <a-button :loading="operatingBan" type="primary" @click="confirmBan(banType)"
          >确定</a-button
        >
      </template>
    </a-modal>
    <!-- 操作记录 -->
    <a-modal
      :title="'操作记录(' + curGHS.ghsName + ')'"
      v-model:visible="recordDialogVisible"
      width="650px"
      @cancel="recordDialogVisible = false"
      @ok="recordDialogVisible = false"
    >
      <a-table
        :columns="recordColumns"
        :dataSource="recordList"
        :pagination="false"
        :loading="recordListLoading"
        bordered
      >
        <template #record="{ record }">
          <span v-if="record.isOpen === 1">开通</span>
          <span v-if="record.isOpen === 0">关闭</span>
          <span v-if="record.isDisable === 1">禁用</span>
          <span v-if="record.isDisable === 0">解禁</span>
        </template>
        <template #note="{ text }">
          {{ text ? text : '---' }}
        </template>
      </a-table>
    </a-modal>
    <a-modal
      :title="contractGHSName + ' - 合同'"
      v-model:visible="contractModalVisible"
      width="1000px"
      @ok="closeContractModal"
      @cancel="closeContractModal"
    >
      <!-- <a-table
        :columns="contractColumns"
        :dataSource="contractList"
        :rowKey="(record) => record.sysid"
        :loading="contractLoading"
        bordered
      >
        <span slot="chargePeriod" slot-scope="row">
          {{ row.startTime }}
          <br />
          ~
          <br />
          {{ row.endTime }}
        </span>
        <span slot="percentage" slot-scope="row">
          {{ Number(row.percentage) * 100 }}%
        </span>
        <span slot="isRetain" slot-scope="row">
          {{ row.isRetain ? '是' : '否 ' }}
        </span>
        <span slot="exPlatform" slot-scope="text">
          {{ text ? text : '---' }}
        </span>
        <span slot="note" slot-scope="text">
          {{ text ? text : '---' }}
        </span>
      </a-table> -->
    </a-modal>
    <a-modal
      title="供应商商品数量限额调整"
      v-model:visible="expansionVisible"
      @cancel="closeExpansion"
      @ok="confirmExpansion"
    >
      <a-form style="padding: 10px">
        <a-form-item label="当前限额"
          >{{ currentItem.limitNum }}
          <a-button type="primary" style="margin-left: 100px" @click="viewOperate"
            >操作记录</a-button
          >
        </a-form-item>
        <a-form-item label="调整后限额">
          <a-input-number
            v-model:value="limitNum"
            :min="1"
            :max="99999999"
            placeholder="请输入8位以内正整数"
            style="width: 200px"
          />
        </a-form-item>
        <a-form-item label="调整依据">
          <a-textarea
            v-model:value="note"
            style="word-break: keep-all; white-space: normal; word-wrap: break-word"
            placeholder="请输入调整原因，例如 扩容合同编码和合同名称、厦大国资处同意函"
          />
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal
      title="操作记录"
      v-model:visible="operateDialogVisible"
      @cancel="closeOperate"
      @ok="closeOperate"
      :width="800"
    >
      <a-table
        :data-source="operateList"
        :columns="operateColumns"
        :pagination="operatePagination"
        :loading="operateListLoading"
        bordered
      />
    </a-modal>
    <a-modal title="区域现货授权管理" v-model:visible="regionalSpotVisible" width="30%">
      <div style="padding: 10px">
        <p style="font-weight: bold">{{ currentItem.ghsName }}</p>
        <a-form>
          <a-form-item label="区域现货授权" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }">
            <a-radio-group name="radioGroup" v-model:value="regionalSpotIsOpen">
              <a-radio value="1">已开通</a-radio>
              <a-radio value="0">未开通</a-radio>
            </a-radio-group>
          </a-form-item>
        </a-form>
        <p style="background-color: #fbe0bb; padding: 5px"
          >由已开通更新为未开通状态时，<span style="color: red"
            >将清空供应商区域现货管理的所有数据，</span
          >请谨慎操作！</p
        >
      </div>
      <template #footer>
        <a-button :loading="operatingBan" @click="cancelRegionalSpot">取消</a-button>
        <a-button :loading="operatingBan" type="primary" @click="confirmRegionalSpot()"
          >提交</a-button
        >
      </template>
    </a-modal>
  </div>
</template>
<script setup>
  import { Modal } from 'ant-design-vue';
  import { ref, onMounted, nextTick } from 'vue';
  import { message } from 'ant-design-vue';
  import {
    // listContractApi,
    listApi,
    createAccountApi,
    batchClosePlatsApi,
    stopPlatAccountApi,
    batchOpenPlatsApi,
    getGhsBondedPlatformApi,
    listInfoAdminApi,
    listContactInfoApi,
    listBingStateApi,
    // updateGhsInfoByGhsCodeApi,
    updatePwdApi,
    updateExPlatformApi,
    listLogAccountManagementApi,
    updateLimitNumApi,
    getLimitLogApi,
    operateisScApi,
  } from '/@/api/super/supplierInfoManage/index';

  const columns2 = [
    { title: '平台名称', dataIndex: 'platName', key: 'platName' },
    { title: '供货商平台编号', dataIndex: 'platSupplierCode', key: 'platSupplierCode' },
    { title: '绑定状态', dataIndex: 'isBonded', key: 'isBonded' },
    { title: '初始密码', dataIndex: 'initPwd', key: 'initPwd' },
    { title: '操作', key: 'operation1', slots: { customRender: 'action' } },
  ];

  const columns = [
    { title: '供货商名称', dataIndex: 'ghsName', key: 'ghsName', align: 'center', width: 110 },
    {
      title: '供货商简称',
      dataIndex: 'ghsShortName',
      key: 'ghsShortName',
      align: 'center',
      width: 90,
    },
    { title: '供货商编号', dataIndex: 'ghsCode', key: 'ghsCode', align: 'center', width: 80 },
    { title: '登录名', dataIndex: 'loginName', key: 'loginName', align: 'center', width: 80 },
    { title: '创建时间', dataIndex: 'createdTime', key: 'createdTime', align: 'center', width: 80 },
    { title: '商品数量限额', dataIndex: 'limitNum', key: 'limitNum', align: 'center', width: 80 },
    {
      title: '区域现货',
      slots: { customRender: 'isScOpen' },
      key: 'isScOpen',
      align: 'center',
      width: 80,
    },
    { title: '是否会员', slots: { customRender: 'isVip' }, align: 'center', width: 80 },
    { title: '已开通', dataIndex: 'platOpened', key: 'platOpened', align: 'center', width: 110 },
    { title: '已绑定', dataIndex: 'platBonded', key: 'platBonded', align: 'center', width: 110 },
    {
      title: '银行信息',
      slots: { customRender: 'hasBankInfo' },
      key: 'hasBankInfo',
      align: 'center',
      width: 120,
    },
    // { title: '专属平台', dataIndex: 'exclusivePlatform', key: 'exclusivePlatform', align: 'center', width: 110 },
    {
      title: '开通',
      key: 'operation',
      slots: { customRender: 'action1' },
      align: 'center',
      width: 75,
    },
    {
      title: '操作',
      key: 'operation1',
      width: 150,
      slots: { customRender: 'action' },
      align: 'center',
    },
  ];
  const openGHSColumns = [
    { title: '平台名称', dataIndex: 'platName' },
    { title: '状态', dataIndex: 'isOpen', slots: { customRender: 'status' }, align: 'center' },
    { title: '操作', slots: { customRender: 'action' }, align: 'center' },
  ];
  const infoColumns = [
    { title: '姓名', dataIndex: 'name', key: 'name' },
    { title: '手机号', dataIndex: 'cellPhone', key: 'cellPhone' },
    { title: '邮箱', dataIndex: 'email', key: 'email' },
    { title: '操作', key: 'operation1', slots: { customRender: 'action' } },
  ];
  const bindingList = ref([]);
  const bindingloading = ref(false);
  const list = ref([]);
  const infoList = ref([]);
  const pagination = ref({
    // 分页配置器
    pageSize: 10, // 一页的数据限制
    current: 1, // 当前页
    total: 0, // 总数
    hideOnSinglePage: false, // 只有一页时是否隐藏分页器
    showQuickJumper: true, // 是否可以快速跳转至某页
    showSizeChanger: false, // 是否可以改变 pageSize
    onChange: (current) => {
      // 切换分页时的回调，
      // 当在页面定义change事件时，切记要把此处的事件清除，因为这两个事件重叠了，可能到时候会导致一些莫名的bug
      pagination.value.current = current;
      getList();
    },
  });
  const searchText = ref('');
  const isVip = ref('');
  const isScOpen = ref('');
  const selectedRowKeys = ref([]);
  const selectedRows = ref([]);
  const listloading = ref(false);
  const listloading1 = ref(true);
  const visible = ref(false);
  const currentItem = ref({});
  const bindingDialog = ref(false);
  const curGHS = ref('');
  const openGHSDialogVisible = ref(false);
  const openGHSDialogData = ref([]);
  const openGHSDialogloading = ref(false);
  const ghsInfoDialogVisible = ref(false);
  const editForm = ref({});
  const confirmLoading = ref(false);
  const pwdForm = ref({
    username: '',
    password: '',
  });
  const pwdFormRef = ref();
  const resetPwdVisible = ref(false);
  const platList = ref({});
  const selectedId = ref(0);
  const changePlatDialog = ref(false);
  const selestedPlist = ref([]);
  const selestedLoading = ref(false);
  const supplierCode = ref('');
  const batchOpening = ref(false);
  // =========禁用供货商============
  const banNoteDialogVisible = ref(false);
  const banNote = ref('');
  const banType = ref('');
  const operatingBan = ref(false);
  const isBatch = ref(false);
  const curPlat = ref({
    platName: '',
    platCode: '',
  });
  // =======操作记录==========
  const recordDialogVisible = ref(false);
  const recordListLoading = ref(false);
  const recordList = ref([]);
  const recordColumns = ref([
    { title: '平台名称', dataIndex: 'platName', width: 100 },
    { title: '操作', slots: { customRender: 'record' }, width: 100 },
    { title: '备注', dataIndex: 'note', slots: { customRender: 'note' }, width: 100 },
    { title: '操作人', dataIndex: 'name', width: 100 },
    { title: '操作时间', dataIndex: 'createTime', width: 100 },
  ]);
  // 查看合同弹窗
  const contractGHSName = ref('');
  const contractModalVisible = ref(false);
  // const contractLoading = ref(false);
  const contractList = ref([]);
  // const contractColumns = ref([
  //   {
  //     title: '周期',
  //     scopedSlots: { customRender: 'chargePeriod' },
  //     key: 'chargePeriod',
  //     align: 'center',
  //     width: '150px',
  //   },
  //   {
  //     title: '收取流水百分比',
  //     scopedSlots: { customRender: 'percentage' },
  //     key: 'percentage',
  //     align: 'center',
  //     width: '100px',
  //   },
  //   { title: '预付款(元)', dataIndex: 'money', key: 'money', align: 'center', width: '100px' },
  //   {
  //     title: '是否沿用',
  //     scopedSlots: { customRender: 'isRetain' },
  //     key: 'isRetain',
  //     align: 'center',
  //     width: '100px',
  //   },
  //   {
  //     title: '会员费',
  //     dataIndex: 'membershipFee',
  //     key: 'membershipFee',
  //     align: 'center',
  //     width: '100px',
  //   },
  //   {
  //     title: '专属平台',
  //     dataIndex: 'exPlatform',
  //     key: 'exPlatform',
  //     align: 'center',
  //     width: '100px',
  //     scopedSlots: { customRender: 'exPlatform' },
  //   },
  //   {
  //     title: '备注',
  //     dataIndex: 'note',
  //     key: 'note',
  //     align: 'center',
  //     width: '100px',
  //     scopedSlots: { customRender: 'note' },
  //   },
  //   {
  //     title: '操作时间',
  //     dataIndex: 'createTime',
  //     key: 'createTime',
  //     align: 'center',
  //     width: '100px',
  //   },
  // ]);
  const expansionVisible = ref(false);
  const limitNum = ref(undefined);
  const note = ref('');
  const operateDialogVisible = ref(false);
  const operateList = ref([]);
  const operateColumns = ref([
    { title: '操作人', dataIndex: 'operator', key: 'operator', align: 'center', width: '100px' },
    {
      title: '操作',
      dataIndex: 'operatorNote',
      key: 'operatorNote',
      align: 'center',
      width: '100px',
    },
    {
      title: '操作类型',
      dataIndex: 'operatorType',
      key: 'operatorType',
      align: 'center',
      width: '100px',
    },
    { title: '操作备注', dataIndex: 'note', key: 'note', align: 'center', width: '100px' },
    {
      title: '操作时间',
      dataIndex: 'operatorTime',
      key: 'operatorTime',
      align: 'center',
      width: '100px',
    },
  ]);
  const operatePagination = ref({
    // 分页配置器
    pageSize: 10, // 一页的数据限制
    current: 1, // 当前页
    total: 0, // 总数
    hideOnSinglePage: false, // 只有一页时是否隐藏分页器
    showQuickJumper: true, // 是否可以快速跳转至某页
    showSizeChanger: false, // 是否可以改变 pageSize
    onChange: (current) => {
      // 切换分页时的回调，
      // 当在页面定义change事件时，切记要把此处的事件清除，因为这两个事件重叠了，可能到时候会导致一些莫名的bug
      operatePagination.value.current = current;
      getOperateList();
    },
  });
  const operateListLoading = ref(false);
  //区域现货
  const regionalSpotVisible = ref(false);
  const regionalSpotIsOpen = ref('');
  onMounted(() => {
    getList();
    getPlatList();
  });
  const closeContractModal = () => {
    contractModalVisible.value = false;
    contractGHSName.value = '';
    contractList.value = [];
  };
  // const showContract = (ghsCode, ghsName) => {
  //   contractModalVisible.value = true;
  //   contractGHSName.value = ghsName;
  //   const param = {
  //     supplierCode: ghsCode,
  //   };
  //   contractLoading.value = true;
  //   listContractApi(param).then((res) => {
  //     if (res.success) {
  //       contractList.value = res.data;
  //     } else {
  //       contractList.value = [];
  //     }
  //     contractLoading.value = false;
  //   });
  // };
  const getPlatList = () => {
    listApi().then((res) => {
      if (res.success) {
        platList.value = res.data;
      } else {
        message.error(res.message);
      }
    });
  };
  const createAccount = (item) => {
    const param = { ghsCode: currentItem.value.ghsCode, plat: item.platCode };
    createAccountApi(param).then((res) => {
      if (res.success) {
        message.success(res.message);
        showBindingDialog(currentItem.value);
      } else {
        message.error(res.message);
      }
    });
  };
  const batchClose = () => {
    if (!selectedRows.value.length) {
      message.warning('请先选择平台');
      return;
    }
    const param = {
      sysids: selectedRowKeys.value.join(','),
    };
    Modal.confirm({
      title: '确认',
      content: `确认关闭以下平台：${selectedRows.value.map((item) => item.platName).join('，')}`,
      okText: '确认关闭',
      cancelText: '取消',
      onOk: () => {
        batchOpening.value = true;
        batchClosePlatsApi(param)
          .then((res) => {
            if (res.success) {
              message.success('关闭成功');
              selectedRows.value = [];
              selectedRowKeys.value = [];
              getList();
              showOpenGHSDialog(curGHS.value);
            } else {
              message.error(res.message);
            }
            batchOpening.value = false;
          })
          .catch(() => {
            batchOpening.value = false;
          });
      },
    });
  };
  const closePlat = (item) => {
    const param = {
      sysids: item.sysid.toString(),
    };
    Modal.confirm({
      title: '确认',
      content: `确认关闭平台${item.platName}吗？`,
      okText: '确认关闭',
      cancelText: '取消',
      onOk: () => {
        batchClosePlatsApi(param).then((res) => {
          if (res.success) {
            message.success('关闭成功');
            showOpenGHSDialog(curGHS.value);
          } else {
            message.error(res.message);
          }
        });
      },
    });
  };
  const batchOpen = () => {
    if (!selectedRows.value.length) {
      message.warning('请先选择平台');
      return;
    }
    const param = {
      sysids: selectedRowKeys.value.join(','),
    };
    Modal.confirm({
      title: '确认',
      content: `确认开通以下平台：${selectedRows.value.map((item) => item.platName).join('，')}`,
      okText: '确认开通',
      cancelText: '取消',
      onOk: () => {
        batchOpening.value = true;
        batchOpenPlatsApi(param)
          .then((res) => {
            if (res.success) {
              message.success('开通成功');
              selectedRows.value = [];
              selectedRowKeys.value = [];
              getList();
              showOpenGHSDialog(curGHS.value);
            } else {
              message.error(res.message);
            }
            batchOpening.value = false;
          })
          .catch(() => {
            batchOpening.value = false;
          });
      },
    });
  };
  // 批量禁用/解禁平台
  const showBanDialog = (banType1, isBatch1, item) => {
    if (!selectedRows.value.length && isBatch1) {
      message.warning('请先选择平台');
      return;
    }
    banType.value = banType1;
    banNoteDialogVisible.value = true;
    isBatch.value = isBatch1;
    if (!isBatch1) {
      curPlat.value = JSON.parse(JSON.stringify(item));
    }
  };
  const closeBanNoteDialog = () => {
    banNoteDialogVisible.value = false;
    banType.value = '';
    banNote.value = '';
    isBatch.value = false;
    curPlat.value.platName = '';
    curPlat.value.platCode = '';
  };
  const confirmBan = (banType) => {
    const param = {
      supplierCode: curGHS.value.ghsCode,
      note: banNote.value,
      type: banType === '禁用' ? '1' : '0',
      platCode: isBatch.value
        ? selectedRows.value.map((item) => item.platCode).join(',')
        : curPlat.value.platCode,
    };
    operatingBan.value = true;
    stopPlatAccountApi(param)
      .then((res) => {
        if (res.success) {
          message.success(res.message);
          selectedRows.value = [];
          selectedRowKeys.value = [];
          closeBanNoteDialog();
          showOpenGHSDialog(curGHS.value);
        } else {
          message.error(res.message);
        }
        operatingBan.value = false;
      })
      .catch(() => {
        operatingBan.value = false;
      });
  };
  const openPlat = (item) => {
    const param = {
      sysids: item.sysid.toString(),
    };
    Modal.confirm({
      title: '确认',
      content: `确认开通平台${item.platName}吗？`,
      okText: '确认开通',
      cancelText: '取消',
      onOk: () => {
        batchOpenPlatsApi(param).then((res) => {
          if (res.success) {
            message.success('开通成功');
            getList();
            showOpenGHSDialog(curGHS.value);
          } else {
            message.error(res.message);
          }
        });
      },
    });
  };
  const onSelectChange = (keys, rows) => {
    selectedRows.value = rows;
    selectedRowKeys.value = keys;
  };
  const showOpenGHSDialog = (text) => {
    curGHS.value = text;
    openGHSDialogVisible.value = true;
    openGHSDialogloading.value = true;
    const param = { supplierCode: text.ghsCode };
    getGhsBondedPlatformApi(param).then((res) => {
      if (res.success) {
        openGHSDialogData.value = res.data;
      } else {
        openGHSDialogData.value = [];
      }
      openGHSDialogloading.value = false;
    });
  };
  const onSearch = () => {
    pagination.value.current = 1;
    getList();
  };
  const getList = () => {
    const param = {
      currentPage: pagination.value.current,
      pageSize: pagination.value.pageSize,
      searchText: searchText.value,
      isVip: isVip.value,
      isScOpen: isScOpen.value,
    };
    listloading.value = true;
    listInfoAdminApi(param).then((res) => {
      if (res.success) {
        list.value = res.data;
        pagination.value.total = res.data[0].total;
      } else {
        list.value = [];
        pagination.value.total = 0;
      }
      listloading.value = false;
    });
  };
  const getContactInfo = (text) => {
    visible.value = true;
    const param = {
      supplierCode: text.ghsCode,
    };
    listContactInfoApi(param).then((res) => {
      if (res.success) {
        infoList.value = res.data;
      } else {
        infoList.value = [];
      }
      listloading1.value = false;
    });
  };
  const showBindingDialog = (item) => {
    bindingDialog.value = true;
    bindingloading.value = true;
    currentItem.value = item;
    const param = { supplierCode: item.ghsCode };
    listBingStateApi(param).then((res) => {
      if (res.success) {
        bindingList.value = res.data;
      } else {
        bindingList.value = [];
      }
      bindingloading.value = false;
    });
  };
  // const editGhsinfo = (item) => {
  //   ghsInfoDialogVisible.value = true;
  //   nextTick(() => {
  //     editForm.value.supplierName = item.ghsName;
  //     editForm.value.supplierShortName = item.ghsShortName;
  //     editForm.value.supplierCode = item.ghsCode;
  //   });
  // };
  const handleOk = (e) => {
    confirmLoading.value = true;
    handleSubmit(e);
  };
  const handlePwdOk = (e) => {
    confirmLoading.value = true;
    handlePwdSubmit(e);
  };
  const handleCancel = () => {
    ghsInfoDialogVisible.value = false;
  };
  const handlePwdCancel = () => {
    resetPwdVisible.value = false;
    confirmLoading.value = false;
  };
  // const handleSubmit = (e) => {
  //   e.preventDefault();
  //   editForm.validateFields((err, values) => {
  //     if (err) {
  //       return;
  //     }
  //     updateGhsInfoByGhsCodeApi(values).then((res) => {
  //       if (res.success) {
  //         message.success(res.message);
  //       } else {
  //         message.error(res.message);
  //       }
  //       ghsInfoDialogVisible.value = false;
  //       getList();
  //       confirmLoading.value = false;
  //     });
  //   });
  // };
  const showResetPwd = (item) => {
    console.log(item);
    resetPwdVisible.value = true;
    nextTick(() => {
      pwdForm.value.username = item.username;
      pwdForm.value.password = '';
      console.log(pwdForm.value);
    });
  };
  // modalFormRef.value.validateFields().then
  const handlePwdSubmit = (e) => {
    e.preventDefault();
    console.log(pwdFormRef.value);
    // return
    pwdFormRef.value
      .validateFields()
      .then((values) => {
        updatePwdApi(values).then((res) => {
          if (res.success) {
            message.success(res.message);
            resetPwdVisible.value = false;
          } else {
            message.warning(res.message);
          }
          confirmLoading.value = false;
        });
      })
      .catch(() => {
        confirmLoading.value = false;
        return;
      });
  };
  // 选择平台
  // const selectPlat = (item) => {
  //   selectedId.value = item.sysid;
  //   changePlatDialog.value = true;
  //   supplierCode.value = item.ghsCode;
  // };
  const changePlatDialogClose = () => {
    selestedPlist.value = [];
    selestedLoading.value = false;
  };
  // 选择平台后确认提交
  const submitChangePlat = () => {
    if (selestedPlist.value.length < 1) {
      return message.warning('请选择平台');
    }
    const param = {
      ghsCode: supplierCode.value,
      exPlatform: selestedPlist.value.join(','),
    };
    selestedLoading.value = true;
    updateExPlatformApi(param).then((res) => {
      if (res.success) {
        message.success(res.message);
        selestedLoading.value = false;
        changePlatDialog.value = false;
        // 更新修改，但不刷新页面
        const selectedItemID = list.value.findIndex((item) => item.sysid === selectedId.value);
        const obj = selestedPlist.value.map((item) => {
          return platList.value.find((e) => e.platCode === item).platName;
        });
        list.value.selectedItemID = {
          ...this.list[selectedItemID],
          exclusivePlatform: obj.join(','),
        };
        // this.$set(this.list, selectedItemID, { ...this.list[selectedItemID], exclusivePlatform: obj.join(',') })
      } else {
        message.error(res.message);
        selestedLoading.value = false;
      }
    });
  };
  const handleChange = (val) => {
    selestedPlist.value = val;
  };
  const showRecord = () => {
    recordDialogVisible.value = true;
    const param = { supplierCode: curGHS.value.ghsCode };
    recordListLoading.value = true;
    listLogAccountManagementApi(param)
      .then((res) => {
        if (res.success) {
          recordList.value = res.data;
        } else {
          recordList.value = [];
        }
        recordListLoading.value = false;
      })
      .catch(() => {
        recordListLoading.value = false;
      });
  };
  const expansion = (item) => {
    currentItem.value = item;
    expansionVisible.value = true;
  };
  const closeExpansion = () => {
    expansionVisible.value = false;
    currentItem.value = {};
    note.value = '';
    limitNum.value = undefined;
  };
  const confirmExpansion = () => {
    if (!limitNum.value) {
      return message.warning('请输入调整后限制');
    }
    const param = {
      ghsCode: currentItem.value.ghsCode,
      limitNum: limitNum.value,
      note: note.value,
    };
    updateLimitNumApi(param).then((res) => {
      if (res.success) {
        message.success('操作成功');
        closeExpansion();
        getList();
      } else {
        message.error(res.message);
      }
    });
  };
  const viewOperate = () => {
    operateDialogVisible.value = true;
    operateList.value = [];
    getOperateList();
  };
  const getOperateList = () => {
    const param = {
      ghsCode: currentItem.value.ghsCode,
      pageIndex: operatePagination.value.current,
      pageSize: operatePagination.value.pageSize,
    };
    operateListLoading.value = true;
    getLimitLogApi(param).then((res) => {
      if (res.success) {
        operateList.value = res.data;
        operatePagination.value.total = res.data[0].total;
      } else {
        operateList.value = [];
        operatePagination.value.total = 0;
      }
      operateListLoading.value = false;
    });
  };
  const closeOperate = () => {
    operateDialogVisible.value = false;
  };
  const showregionalSpotVisible = (item) => {
    currentItem.value = item;
    regionalSpotVisible.value = true;
  };
  const cancelRegionalSpot = () => {
    regionalSpotVisible.value = false;
    regionalSpotIsOpen.value = '';
  };
  const confirmRegionalSpot = () => {
    if (!regionalSpotIsOpen.value) {
      return message.warning('请选择是否开通区域管理');
    }
    const param = {
      supplierCode: currentItem.value.ghsCode,
      type: regionalSpotIsOpen.value,
    };
    //未开通 清数据量太大，先关闭弹窗，接口报错不影响后端清数据
    if (regionalSpotIsOpen.value === '0') {
      message.success('正在清理供应商现货管理的所有数据，请耐心等候！');
      cancelRegionalSpot();
    }
    operateisScApi(param).then((res) => {
      if (res.success) {
        message.success(res.message);
      } else {
        message.error(res.message);
      }
      cancelRegionalSpot();
      getList();
    });
  };
  const onReSet = () => {
    searchText.value = '';
    isVip.value = '';
    isScOpen.value = '';
  };
</script>

<style lang="scss" scoped></style>
<style>
  /* .error {
    background: red;
  } */
</style>
