<template>
  <view class="amms-page">
    <cu-custom :showUser="false" :showChange="false">
      <block v-slot:content>设置</block>
    </cu-custom>
    <!--  -->
    <view class="list">
      <view class="work_nav">
        <view class="container">
          <view class="item" @tap="clickCountFun">
            <view class="left">当前版本号</view>
            <view class="right">
              <view class="n">{{ appVersion }}</view>
            </view>
          </view>
          <block v-if="clickCount > 6">
            <view class="x"></view>
            <view class="item">
              <view class="left">接口地址</view>
              <view class="right">
                <view
                  @tap="urlPrefixVisible = true"
                  class="n"
                  :class="urlPrefix ? '' : 'amms-main-sub-color'"
                >
                  {{ urlPrefix ? urlPrefix : "请选择接口配置" }}
                </view>
                <w-picker
                  :visible.sync="urlPrefixVisible"
                  mode="selector"
                  default-type="name"
                  :options="urlPrefixList"
                  @confirm="onConfirm($event, 'urlPrefix')"
                  @cancel="onCancel"
                  ref="urlSelector"
                ></w-picker>
                <image class="icon" :src="iconImg"></image>
              </view>
            </view>
          </block>
          <view class="x"></view>
          <view class="item" @click="appVersionClick">
            <view class="left">检查更新</view>
            <view class="right">
              <image class="icon" :src="iconImg"></image>
            </view>
          </view>
          <!-- <view class="x"></view> -->
          <!-- <view class="item">
						<view class="left">是否开启指纹登录</view>
						<view class="right">
							<switch @change="switch1Change" checked color="#166CE5" style="transform:scale(0.7)" />
						</view>
					</view> -->
          <!-- <view class="x"></view>
					<view class="item">
						<view class="left">菜单排序</view>
						<view class="right">
							<image class="icon" :src="iconImg"></image>
						</view>
					</view> -->
        </view>
      </view>
      <!--  -->
      <view class="work_nav">
        <view class="container">
          <view class="item">
            <view class="left">默认工作仓库</view>
            <view class="right" @tap="showWarehousePicker">
              <view class="n" :class="warehouse ? '' : 'amms-main-sub-color'">
                {{ warehouse ? warehouse : "请选择工作仓库" }}
              </view>
              <view v-if="warehouse" @tap.stop="clearSetting('warehouse')">
                <uni-icons type="clear" size="28" color="#dddddd"></uni-icons>
              </view>
              <image class="icon" :src="iconImg"></image>
            </view>
            <drawer-picker
              ref="warehousePicker"
              @recall="listenToWarehouse"
              :originData="warehouseList"
            ></drawer-picker>
          </view>
          <view class="x"></view>
          <view class="item">
            <view class="left">默认工作航站</view>
            <view class="right" @tap="toPickTerminal()">
              <view class="n" :class="terminal ? '' : 'amms-main-sub-color'">
                {{
                  terminal ? `${terminal}-${terminalName}` : "请选择工作航站"
                }}
              </view>
              <view v-if="terminal" @tap.stop="clearSetting('terminal')">
                <uni-icons type="clear" size="28" color="#dddddd"></uni-icons>
              </view>
              <image class="icon" :src="iconImg"></image>
            </view>
          </view>
          <view class="x"></view>
          <view class="item">
            <view class="left">默认工作库存地</view>
            <view class="right" @tap="showStockLocationPicker">
              <view
                class="n"
                :class="stockLocation ? '' : 'amms-main-sub-color'"
              >
                {{ stockLocation ? stockLocation : "请选择工作库存地" }}
              </view>
              <view
                v-if="stockLocation"
                @tap.stop="clearSetting('stockLocation')"
              >
                <uni-icons type="clear" size="28" color="#dddddd"></uni-icons>
              </view>
              <image class="icon" :src="iconImg"></image>
            </view>
            <drawer-picker
              ref="stockLocationPicker"
              @recall="listenToStockLocation"
              :originData="stockLocationList"
            ></drawer-picker>
          </view>
          <view class="x"></view>
          <view class="item">
            <view class="left">设置所在城市</view>
            <view class="right">
              <view
                @tap="showCity = true"
                class="n"
                :class="addressData.areaValue ? '' : 'amms-main-sub-color'"
              >
                {{
                  addressData.formatLabel
                    ? addressData.formatLabel
                    : "请选择所在城市"
                }}
              </view>
              <cc-selectDity
                :province="province"
                :city="city"
                :area="area"
                :show="showCity"
                @changeClick="changeClick"
                @sureSelectArea="onsetCity"
                @hideShow="onhideShow"
              ></cc-selectDity>
              <image class="icon" :src="iconImg"></image>
            </view>
          </view>
          <view class="x"></view>
          <view class="item">
            <view class="left">默认打印机</view>
            <view class="right">
              <view
                @tap="printerVisible = true"
                class="n"
                :class="printer ? '' : 'amms-main-sub-color'"
              >
                {{ printer ? printer : "请选择默认打印机" }}
              </view>
              <w-picker
                :visible.sync="printerVisible"
                mode="selector"
                default-type="name"
                :default-props="printerProps"
                :options="printerList"
                @confirm="onConfirm($event, 'printer')"
                @cancel="onCancel"
                ref="selector"
              ></w-picker>
              <image class="icon" :src="iconImg"></image>
              <button
                class="cu-btn bg-blue margin-left-xs shadow"
                @tap="printjobTestFun"
                :disabled="printDisabled"
              >
                测试
              </button>
            </view>
          </view>
        </view>
      </view>

      <!--  -->
      <view class="work_nav">
        <view class="container">
          <view
            class="item"
            @click="path_url('/pages/home/components/stagingHelp')"
          >
            <view class="left">使用帮助</view>
            <view class="right">
              <image class="icon" :src="iconImg"></image>
            </view>
          </view>
          <block v-if="loginType == 'normal'">
            <view class="x"></view>
            <view
              class="item"
              @click="path_url('/pages/home/components/editPassword')"
            >
              <view class="left">外站用户更改密码</view>
              <view class="right">
                <image class="icon" :src="iconImg"></image>
              </view>
            </view>
          </block>
        </view>
      </view>
      <view class="but">
        <view class="container">
          <view @tap="logout" class="amms-main-button">退出登录</view>
        </view>
      </view>
      <q-loading mask="true" click="true" ref="loading"></q-loading>
    </view>
  </view>
</template>

<script setup lang="ts">
// import { uuid } from '../../utils';
import { ref, getCurrentInstance, onMounted } from "vue";
import drawerPicker from "../../components/drawerPicker";
import { onShow, onLoad } from "@dcloudio/uni-app";
import { request } from "@/utils/request";
import { secondGenerationAppUpdate } from "@/common/appUpdate.js";
import { clearStorageFun } from "@/common/index.js";

const { proxy } = getCurrentInstance();
const loginType = ref(uni.getStorageSync("loginType"));
const iconImg = ref("../../../static/img/ammsHome/icon1.png");
const warehouse = ref("");
const warehouseList = ref([]);
const terminal = ref("");
const terminalName = ref("");
const stockLocation = ref("");
const stockLocationList = ref([]);
const isToPickTerminal = ref(false);
let appVersion = ref("0");
// 打印机
const printer = ref("");
const printerVisible = ref(false);
const printerProps = ref({
  label: "registerName",
  value: "id",
});
const printerList = ref([]);
const printDisabled = ref(false);
// 接口地址切换
const urlPrefix = ref("");
const urlPrefixVisible = ref(false);
const urlPrefixList = ref([
  {
    label: "http://10.127.12.11:8080",
    value: "http://10.127.12.11:8080",
  },
  {
    label: "http://10.70.74.191:80",
    value: "http://10.70.74.191:80",
  },
  {
    label: "https://amms.hnatechnic.com",
    value: "https://amms.hnatechnic.com",
  },
  {
    label: "http://10.52.28.110:80",
    value: "http://10.52.28.110:80",
  },
  {
    label: "https://amms.hnatechnic.com:8443",
    value: "https://amms.hnatechnic.com:8443",
  },
]);
const clickCount = ref(0);
const province = ref("海南省");
const showCity = ref(false);
const city = ref("海口市");
const area = ref("美兰区");
const areaCode = ref("460108");
const addressData = ref({
  areaValue: "",
  formatLabel: "",
});

onMounted(() => {
  // 获取授权打印机
  getAuthPrinter();
});

onLoad(() => {
  getWarehouseDict();
  getStockLocationList();
  let addrress = uni.getStorageSync("ammsArea");
  if (addrress) {
    let arr = addrress.split("-");
    addressData.value = {
      areaValue: arr[2],
      formatLabel: addrress,
    };
  }
  // 监听站点选择回调
  uni.$off("cityPicker");
  uni.$on("cityPicker", (res: any) => {
    if (res) {
      terminal.value = res.split("-")[0];
      terminalName.value = res.split("-")[1];
      uni.setStorageSync("userTerminal", terminal.value);
      uni.setStorageSync("userTerminalName", terminalName.value);
      setDefaultTerminalFun();
    }
  });
});

onShow(() => {
  // 设置仓库
  warehouse.value = uni.getStorageSync("userWarehouse");
  // 设置航站
  if (!isToPickTerminal.value) {
    terminal.value = uni.getStorageSync("userTerminal");
    terminalName.value = uni.getStorageSync("userTerminalName");
  }
  // 设置库存地
  stockLocationList.value = uni.getStorageSync("stockLocationList") || [];
  stockLocation.value = uni.getStorageSync("userStock");
  // 设置打印架
  printerList.value = uni.getStorageSync("userPrinterList") || [];
  printer.value =
    uni.getStorageSync("userDefaultPrinter") &&
    typeof uni.getStorageSync("userDefaultPrinter").registerName != "undefined"
      ? uni.getStorageSync("userDefaultPrinter").registerName
      : "";

  // 获取版本号
  let clent = uni.getSystemInfoSync();
  let version = "0";
  // #ifdef APP
  version = clent.appWgtVersion;
  // #endif
  // #ifdef H5
  version = clent.appVersion;
  // #endif
  uni.setStorageSync("appVersion", version);
  appVersion.value = uni.getStorageSync("appVersion");
});
function onhideShow() {
  showCity.value = false;
}
//选中省市区
function onsetCity(e: any) {
  console.log(e);
  let data = e.detail.target.dataset;
  let address = `${data.province}-${data.city}-${data.area}`;
  showCity.value = false;
  addressData.value = {
    areaValue: data.area,
    formatLabel: address,
  };
  uni.setStorageSync("ammsArea", address);
}
function changeClick(value: any, value2: any, value3: any, value4: any) {
  province.value = value;
  city.value = value2;
  area.value = value3;
  areaCode.value = value4;
}
// 删除设置
function clearSetting(type: string) {
  // 默认工作仓库
  if (type == "warehouse") {
    warehouse.value = "";
    uni.setStorageSync("userWarehouse", "");
    setDefaultWarehouseFun("");
  }
  // 默认工作航站
  if (type == "terminal") {
    terminal.value = "";
    terminalName.value = "";
    uni.setStorageSync("userTerminal", "");
    uni.setStorageSync("userTerminalName", "");
    setDefaultTerminalFun();
  }
  // 默认工作库存地
  if (type == "stockLocation") {
    stockLocation.value = "";
    uni.setStorageSync("userStock", "");
    setDefaultStocklocationFun("");
  }
}

function onConfirm(res: any, type: string) {
  if (type == "printer") {
    printer.value = res.result;
    uni.setStorageSync("userDefaultPrinter", res.obj);
    setDefaultPrinter(res.obj.id);
  } else if (type == "urlPrefix") {
    uni.setStorageSync("urlPrefix", res.result);
    urlPrefix.value = res.result;
    // 重启应用
    uni.showToast({
      title: "切换接口地址成功，将自动重启应用",
      icon: "none",
    });
    setTimeout(function () {
      if (typeof plus != "undefined") {
        plus.runtime.restart();
      }
    }, 3000);
  }
  onCancel();
}

function onCancel() {
  printerVisible.value = false;
  urlPrefixVisible.value = false;
}
// 设置默认打印机
function setDefaultPrinter(printerId: any) {
  request(
    {
      url: "setDefaultPrinter",
      method: "post",
      data: {
        printerId: printerId,
      },
    },
    false,
    true
  )
    .then((res: any) => {
      if (res.code == 0) {
        uni.showToast({
          title: "成功设置默认打印机",
          icon: "none",
          duration: 3000,
        });
      }
    })
    .catch((err: any) => {
      console.log(err);
    });
}
// 获取授权打印机
function getAuthPrinter() {
  request({
    url: "auth_printer",
    method: "get",
  })
    .then((res: any) => {
      if (res.code == 0) {
        uni.setStorageSync("userPrinterList", res.data);
        let lists = res.data;
        let blnDefaultPrinter = false;
        lists.forEach((item: any) => {
          if (item.defaultPrinter == true) {
            uni.setStorageSync("userDefaultPrinter", item);
            blnDefaultPrinter = true;
          }
        });
        if (!blnDefaultPrinter) {
          uni.setStorageSync("userDefaultPrinter", "");
        }
      }
    })
    .catch((err: any) => {
      console.log(err);
    });
}
// 打印机打印测试页
function printjobTestFun() {
  printDisabled.value = true;
  let userPrinter = uni.getStorageSync("userDefaultPrinter");
  if (!userPrinter) {
    uni.showToast({
      title: "请选择默认打印机",
      icon: "none",
    });
    return;
  }
  let requestData = {
    printerId: userPrinter.id,
  };
  request(
    {
      url: "printjobTest",
      method: "post",
      data: requestData,
    },
    false,
    true
  )
    .then((res: any) => {
      if (res.code == 0) {
        uni.showModal({
          title: "提示",
          content: "已提交测试到打印页，请到对应打印机查收。",
          success: function (res) {
            printDisabled.value = false;
            if (res.confirm) {
              console.log("用户点击确定");
            } else if (res.cancel) {
              console.log("用户点击取消");
            }
          },
        });
      } else if (res.code == 1) {
        uni.showToast({
          title: res.msg,
          icon: "none",
          duration: 3000,
        });
      }
    })
    .catch((err) => {
      printDisabled.value = false;
    });
}
// 版本号点击次数统计
function clickCountFun() {
  clickCount.value++;
}

// 选择航站
function toPickTerminal() {
  uni.navigateTo({
    url: "/pages/components/cityPicker",
    complete: () => {
      isToPickTerminal.value = true;
    },
  });
}

// 展开工作仓库抽屉
function showWarehousePicker() {
  // this.goTop();
  proxy.$refs.warehousePicker.showDrawer({
    type: "warehouse",
    currentValue: warehouse,
  });
}

// 展开库存地抽屉
function showStockLocationPicker() {
  // this.goTop();
  proxy.$refs.stockLocationPicker.showDrawer({
    type: "stockLocation",
    currentValue: stockLocation,
  });
}

function listenToStockLocation(res: string) {
  for (let i = 0; i < stockLocationList.value.length; i++) {
    if (stockLocationList.value[i]["value"] == res) {
      uni.setStorageSync("userStock", res);
      setDefaultStocklocationFun(stockLocationList.value[i].id);
      break;
    }
  }
  stockLocation.value = res;
}
function listenToWarehouse(res: any) {
  for (let i = 0; i < warehouseList.value.length; i++) {
    if (warehouseList.value[i]["value"] == res) {
      uni.setStorageSync("userWarehouse", res);
      setDefaultWarehouseFun(warehouseList.value[i].id);
      break;
    }
  }
  warehouse.value = res;
}
// 获取仓库数据
function getWarehouseDict() {
  request({
    method: "GET",
    url: "getWarehouseDict",
  })
    .then((res: any) => {
      if (res.code == 0) {
        let arr: any = [];
        res.data.map((ele: any) => {
          arr.push(ele);
        });
        warehouseList.value = arr;
        uni.setStorageSync("warehouseList", arr);
      }
    })
    .catch((err: any) => {
      console.log(err);
    });
}
// 获取库存地数据
function getStockLocationList() {
  let requestData = {
    current: 1,
    size: 10000,
  };
  request({
    url: "appstocklocation-page2",
    method: "get",
    data: requestData,
  })
    .then((res: any) => {
      if (res.code == 0) {
        stockLocationList.value = res.data.list;
        uni.setStorageSync("stockLocationList", res.data.list);
      } else if (res.code == 1) {
        uni.showToast({
          title: res.msg,
          icon: "none",
          duration: 3000,
        });
      }
    })
    .catch((err: any) => {
      console.log(err);
    });
}
// 设置默认仓库
function setDefaultWarehouseFun(warehouseId: String) {
  proxy.$refs.loading.open();
  let appUserWarehouse = {
    defaultFlag: "0",
    warehouseId: warehouseId.toString(),
    userName: uni.getStorageSync("username"),
  };
  request({
    url: "setDefaultWarehouse",
    method: "put",
    data: appUserWarehouse,
  })
    .then((res: any) => {
      proxy.$refs.loading.close();
      if (res.code == 0) {
        uni.showToast({
          title: "成功修改默认仓库",
          icon: "none",
          duration: 3000,
        });
        uni.$emit("updateTabInfo", null);
      }
    })
    .catch((err: any) => {
      proxy.$refs.loading.close();
      console.log(err);
    });
}
// 设置默认航站
function setDefaultTerminalFun() {
  proxy.$refs.loading.open();
  let appUserTerminal = {
    defaultFlag: "0",
    terminalId: terminal.value,
    userName: uni.getStorageSync("username"),
  };
  request({
    url: "setDefaultTerminal",
    method: "put",
    data: appUserTerminal,
  })
    .then((res: any) => {
      proxy.$refs.loading.close();
      if (res.code == 0) {
        uni.showToast({
          title: "成功修改默认航站",
          icon: "none",
          duration: 3000,
        });
        uni.$emit("updateTabInfo", null);
      }
    })
    .catch((err: any) => {
      proxy.$refs.loading.close();
      console.log(err);
    });
}
// 设置默认库存地
function setDefaultStocklocationFun(stockLocationId: any) {
  proxy.$refs.loading.open();
  let appUserStockLocation = {
    defaultFlag: "0",
    stockLocationId: stockLocationId.toString(),
    userName: uni.getStorageSync("username"),
  };
  request({
    url: "setDefaultStocklocation",
    method: "put",
    data: appUserStockLocation,
  })
    .then((res: any) => {
      proxy.$refs.loading.close();
      if (res.code == 0) {
        uni.showToast({
          title: "成功修改默认库存地",
          icon: "none",
          duration: 3000,
        });
        uni.$emit("updateTabInfo", null);
      }
    })
    .catch((err: any) => {
      proxy.$refs.loading.close();
      console.log(err);
    });
}

function switch1Change(_val: any) {
  console.log(_val.detail.value);
}

function path_url(_page: any) {
  uni.navigateTo({
    url: _page,
  });
}

// 退出登录
function logout() {
  proxy.$refs.loading.open();
  request({
    url: "logout",
    method: "delete",
  })
    .then((res: any) => {
      proxy.$refs.loading.close();
      if (res.code == 0) {
        uni.showToast({
          title: "退出登录成功",
          icon: "success",
        });
        uni.removeStorageSync("access_token");
        uni.removeStorageSync("refresh_token");
        // 若存在window对象，则可以判断当前为使用H5的方式打开，记录下跳转前的页面地址
        if (typeof window != "undefined") {
          uni.setStorageSync("preUrl", "/pages/home/homeIndex");
        }
        if (uni.getStorageSync("loginType") == "iam") {
          // 域账号登录退出
          clearStorageFun();
          uni.setStorageSync("blnLogout", true);
          if (typeof window != "undefined") {
            window.location.href = `https://login.hnagroup.com/ngiam-rst/cas/logout?backUrl=${encodeURIComponent(
              location.origin + apiMapper["iam-h5"]
            )}&timestamp=${new Date().getTime()}`;
          } else {
            if (urlPrefix.value.indexOf("amms.hnatechnic.com") > -1) {
              setTimeout(function () {
                uni.navigateTo({
                  url: "/pages/login/iam-formal?blnLogout=true",
                });
              }, 1000);
            } else {
              setTimeout(function () {
                uni.navigateTo({
                  url: "/pages/login/iam?blnLogout=true",
                });
              }, 1000);
            }
          }
        } else {
          // 普通登录退出
          clearStorageFun();
          setTimeout(function () {
            uni.redirectTo({
              url: "/pages/login/index",
            });
          }, 1000);
        }
      }
    })
    .catch((err: any) => {
      console.log(err);
      proxy.$refs.loading.close();
      uni.showToast({
        title: "退出登录失败",
        icon: "none",
      });
      return;
    });
}

function appVersionClick() {
  let clent = uni.getSystemInfoSync();
  console.log(clent);
  if (clent.platform == "android") {
    secondGenerationAppUpdate(uni.getStorageSync("appVersion") || 0, "Android");
  } else {
    secondGenerationAppUpdate(uni.getStorageSync("appVersion") || 0, "IOS");
  }
}
</script>

<style lang="scss" scoped>
.home {
  background-color: #f2f6f9;
  height: 100%;
}

.bj {
  background: linear-gradient(226deg, #168aff 0%, #0e57ff 100%);
  border-radius: 0rpx 0rpx 32rpx 32rpx;
  padding-bottom: 125rpx;
}

.container {
  padding: 0rpx 32rpx;
}

//
.head {
  .container {
    display: flex;
    justify-content: space-between;
    font-size: 36rpx;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #ffffff;
    padding: 10rpx 32rpx;
    background: linear-gradient(226deg, #168aff 0%, #0e57ff 100%);

    .pic {
      width: 44rpx;
      height: 44rpx;
    }
  }
}

//
.list {
  // margin-top: 100rpx;
}

//
.work_nav {
  background: #ffffff;
  margin-bottom: 24rpx;

  .container {
    .item {
      padding: 28rpx 0rpx;
      font-size: 30rpx;
      font-family: PingFangSC-Regular, PingFang SC;
      font-weight: 400;
      color: #444d54;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .right {
        display: flex;
        align-items: center;
        justify-content: flex-end;

        .icon {
          width: 20rpx;
          height: 20rpx;
          margin: 0;
          margin-left: 16rpx;
        }
      }
    }

    .x {
      border-bottom: 1rpx solid #dddddd;
    }
  }
}

.but {
  margin-top: 48rpx;

  uni-button {
    font-size: 30rpx;
    font-weight: 500;
    color: #ffffff;
    background-color: #166ce5;
  }

  .is-hover {
    color: rgba(255, 255, 255, 0.6);
    background-color: #179b16;
    border-color: #179b16;
  }
}
</style>
