<template>
  <div class="box-main">
    <div class="box-body">
      <MomTable
        ref="MomTable"
        :row-selection="rowSelection"
        :query-param="queryForm"
        :query-param-item="queryFormItem"
        row-key="id"
        :page.sync="page"
        :total="total"
        :columns="tableColumns"
        :data-source="tableData"
        :action-buttons="tableAction"
        @release="handleRelease"
        @download="handleDownload"
        @edit="handleEdit"
        @delete="handleDelete"
        @search="searchPageData"
      >
        <a-row slot="toolbar">
          <!-- 新增 -->
          <a-button
            v-if="hasAuth('APP_MANAGEMENT:ADD')"
            @click="handleOpenDrawer('add')"
          >
            <a-icon type="plus" />
            {{ $t("ADD") }}
          </a-button>
          <a-button
            v-if="hasAuth('APP_MANAGEMENT:BATCH_DELETE')"
            type="danger"
            icon="delete"
            @click="handDelete"
          >
            {{ $t("BATCH_DELETE") }}
          </a-button>
        </a-row>
        <template slot="appCode" slot-scope="text, record">
          <span>{{ formatData(appNameList, record.appCode) }}</span>
        </template>
        <template slot="isForce" slot-scope="text, record">
          <span v-if="record.isForce === 'Y'">{{ $t("YES") }}</span>
          <span v-if="record.isForce === 'N'">{{ $t("NO") }}</span>
        </template>
        <template slot="isAll" slot-scope="text, record">
          <span v-if="record.isAll === 'Y'">{{ $t("YES") }}</span>
          <span v-if="record.isAll === 'N'">{{ $t("NO") }}</span>
        </template>
        <template slot="status" slot-scope="text, record">
          <span
            :style="record.status === 'PUBLISHED' ? 'color: #0fd19c' : ''"
            >{{ formatData(stateList, record.status) }}</span
          >
        </template>
        <template slot="logo" slot-scope="text, record">
          <Icon :type="record.logo" :size="16" />
        </template>
      </MomTable>
    </div>

    <!-- 新增、编辑弹框 -->
    <MegaDrawer
      :append-to-body="true"
      :visible.sync="drawer"
      :title="drawerType !== 'edit' ? `${$t('ADD')}` : `${$t('EDIT')}`"
      :wrapper-closable="false"
      destroy-on-close
      width="520"
      @cancel="handleCancel"
      @close="handleCancel"
      @ok="handleSave"
    >
      <div slot="main">
        <a-form-model
          ref="formRef"
          layout="vertical"
          :model="formData"
          :rules="rules"
        >
          <!-- 类型 -->
          <a-form-model-item :label="$t('APP_NAME')" prop="appCode">
            <i-table-select
              v-model="formData.appCode"
              :options="queryFormItem.appCode.options"
              :disabled="drawerType == 'edit'"
              @change="handChange"
            />
          </a-form-model-item>
          <!-- 应用logo -->
          <a-form-model-item :label="$t('APPLICATION_LOGO')" prop="logo">
            <IconList v-model="formData.logo" style="width: 100%" />
          </a-form-model-item>
          <!-- APP版本 -->
          <a-form-model-item :label="$t('APP_VERSION')" prop="appVersion">
            <a-input
              v-model="formData.appVersion"
              :disabled="drawerType == 'edit'"
              allow-clear
            />
          </a-form-model-item>
          <!-- APP版本名称 -->
          <a-form-model-item
            :label="$t('APP_VERSION_NAME')"
            prop="appVersionName"
          >
            <a-input v-model="formData.appVersionName" allow-clear />
          </a-form-model-item>
          <!-- 强制升级 -->
          <a-form-model-item :label="$t('FORCED_UPGRADE')" prop="isForce">
            <a-radio-group v-model="formData.isForce">
              <a-radio value="Y">{{ $t("YES") }}</a-radio>
              <a-radio value="N">{{ $t("NO") }}</a-radio>
            </a-radio-group>
          </a-form-model-item>
          <!-- 全部升级 -->
          <a-form-model-item :label="$t('UPGRADE_ALL')" prop="isAll">
            <a-radio-group v-model="formData.isAll">
              <a-radio value="Y">{{ $t("YES") }}</a-radio>
              <a-radio value="N">{{ $t("NO") }}</a-radio>
            </a-radio-group>
          </a-form-model-item>
          <!-- apk文件 -->
          <a-form-model-item :label="$t('APK_FILE')">
            <div style="position: absolute; top: -7px; left: -78px; color: red">
              *
            </div>
            <MegaUploader
              ref="upload"
              :options="options"
              @fileSuccess="uploadSuccess"
            >
              <a-button type="primary">
                {{ $t("UPLOAD") }}
              </a-button>
            </MegaUploader>
          </a-form-model-item>
          <a-form-model-item
            :label="$t('APPLICATION_DESCRIPTION')"
            prop="appDescribe"
          >
            <a-input v-model="formData.appDescribe" />
          </a-form-model-item>
          <!-- 备注 -->
          <a-form-model-item :label="$t('REMARK')" prop="remark">
            <a-input
              v-model="formData.remark"
              type="textarea"
              :row="2"
              :placeholder="$t('PLACEENTER')"
              allow-clear
            />
          </a-form-model-item>
          <a-form-model-item
            v-if="formData.isAll === 'N'"
            :label="$t('TERMINAL_ID')"
            prop="deviceIds"
            :rules="{
              required: true,
              message: $t('PLACEENTER'),
              trigger: 'change',
            }"
          >
            <!-- 选择终端 -->
            <SelectTerminal
              ref="selectTerminalRef"
              row-key="id"
              show-key="deviceId"
              :base-terminal-status-list="baseTerminalStatusList"
              :base-terminal-type-list="baseTerminalTypeList"
              :default-selected-rows="formData.deviceIds"
              style="position: relative"
              @confirm="getReturnData"
            />
          </a-form-model-item>
        </a-form-model>
      </div>
    </MegaDrawer>
  </div>
</template>

<script>
import {
  Drawer as MegaDrawer,
  Uploader as MegaUploader,
  Icon,
  IconList,
} from "@mega-design/ui-vue";
import { getToken } from "@/utils/auth";
import { fetchFileUrl } from "@/utils/file";
import ApiConstant from "@/api/ApiConstant";

export default {
  name: "Label",
  // eslint-disable-next-line vue/no-unused-components
  components: { MegaDrawer, MegaUploader, Icon, IconList },
  data() {
    return {
      deviceIdList: [],
      options: {
        target: `${ApiConstant.PREFIX_CORE}/api/sys/file/upload/chunk`,
        headers: {
          Authorization: this.$auth.getToken("local"),
          tenantId:
            this.$store.state.app.systemConfig.TENANT_OPEN === "true"
              ? this.$store.state.account.tenantId
              : "",
        },
        testChunks: true,
        chunkSize: 10 * 1024 * 1024,
        singleFile: true,
      },
      headers: {
        Authorization: getToken(),
      },
      // 查询sort
      sortParams: null,
      // 查询表单数据
      queryForm: {
        appVersion: "",
        appCode: null,
        status: "",
      },
      paramNames: [],
      tableData: [],
      total: 0,
      page: 1,
      drawer: false,
      drawerPreview: false,
      drawerType: "add",
      appNameList: [],
      formData: {
        type: "",
        appVersion: "",
        appVersionName: "",
        isForce: "Y",
        isAll: "Y",
        fileCode: "",
        fileUrl: "",
        remark: "",
        logo: "",
        appDescribe: "",
        deviceIds: [],
      },
      fileFormData: null,
      form: null,
      isSuccessFile: false,
      imgSrc: "", // 预览图片
      isUpload: false, // 是否上传文件
      stateList: [],
      fileCode: "",
      fileUrl: "",
      tableAction: [
        (h, value, a, b) => (
          <span
            disabled={value.record.status !== "WAIT_PUBLISH"}
            onClick={() => this.handleRelease(value.record)}
          >
            {this.hasAuth("APP_MANAGEMENT:RELEASE") && (
              <Icon
                type="icon-cur-release"
                size={15}
                style="color:#3dc2e5;cursor: pointer;"
                title={this.$t("RELEASE")}
              />
            )}
          </span>
        ),
        (h, value, a, b) =>
          this.hasAuth("APP_MANAGEMENT:DOWNLOAD") && (
            <span onClick={() => this.handleDownload(value.record)}>
              <Icon
                type="icon-dir-f-upload"
                size={20}
                style="color:#3dc2e5"
                title={this.$t("DOWNLOAD")}
              />
            </span>
          ),
        (h, value, a, b) => (
          <span
            disabled={value.record.status !== "WAIT_PUBLISH"}
            onClick={() => this.handleEdit(value.record)}
          >
            {this.hasAuth("APP_MANAGEMENT:EDIT") && (
              <Icon
                type="icon-edit-edit"
                size={15}
                style="color:#3dc2e5"
                title={this.$t("EDIT")}
              />
            )}
          </span>
        ),
        (h, value, a, b) =>
          this.hasAuth("APP_MANAGEMENT:DELETE") && (
            <span onClick={() => this.handleDelete(value.record)}>
              <Icon
                type="icon-edit-delete"
                size={18}
                style="color:#d45f5f"
                title={this.$t("DELETE")}
              />
            </span>
          ),
      ],
      selectedRowKeys: [],
      baseTerminalStatusList: [],
      baseTerminalTypeList: [],
    };
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
        },
      };
    },
    rules() {
      const rulesObj = {
        appCode: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "blur",
          },
        ],
        appVersion: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
          {
            pattern: /^[+]?\d{1,4}(?:\.\d{1,2})?$/,
            message: this.$t("APP_CLIENT_WARNING"),
          },
        ],
        appVersionName: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        isForce: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "change",
          },
        ],
        isAll: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "change",
          },
        ],
        remark: [
          {
            max: 64,
            message: this.$t("PLACEENTER") + 64 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
      };
      return rulesObj;
    },
    queryFormItem() {
      return this.$observable("queryFormItem", {
        appVersion: {
          label: () => this.$t("APP_VERSION"),
        },
        // 类型
        appCode: {
          label: () => this.$t("APP_NAME"),
          itemType: "select",
          isRequired: false,
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
        },
        // 状态
        status: {
          label: () => this.$t("STATUS"),
          itemType: "select",
          isRequired: false,
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
        },
      });
    },
    tableColumns() {
      return [
        // APP名称
        {
          dataIndex: "appCode",
          title: () => this.$t("APP_NAME"),
          width: 180,
          scopedSlots: { customRender: "appCode" },
        },
        // 应用logo
        {
          dataIndex: "logo",
          title: () => this.$t("APPLICATION_LOGO"),
          width: 180,
          sorter: false,
          ellipsis: true,
          scopedSlots: { customRender: "logo" },
        },
        // APP版本
        {
          dataIndex: "appVersion",
          title: () => this.$t("APP_VERSION"),
          width: 150,
        },
        // APP版本名称
        {
          dataIndex: "appVersionName",
          title: () => this.$t("APP_VERSION_NAME"),
          width: 160,
        },
        // 强制升级
        {
          dataIndex: "isForce",
          sorter: false,
          title: () => this.$t("FORCED_UPGRADE"),
          scopedSlots: { customRender: "isForce" },
          width: 120,
        },
        // 全部升级
        {
          dataIndex: "isAll",
          sorter: false,
          scopedSlots: { customRender: "isAll" },
          title: () => this.$t("UPGRADE_ALL"),
          width: 120,
        },
        // 状态
        {
          dataIndex: "status",
          sorter: false,
          scopedSlots: { customRender: "status" },
          title: () => this.$t("STATUS"),
          width: 180,
        },
        // 应用描述
        {
          dataIndex: "appDescribe",
          title: () => this.$t("APPLICATION_DESCRIPTION"),
          sorter: false,
          ellipsis: true,
          width: 180,
        },
        // 备注
        {
          dataIndex: "remark",
          sorter: false,
          title: () => this.$t("REMARK"),
          minWidth: 200,
        },
        // 更新人员
        {
          dataIndex: "updateBy",
          sorter: false,
          title: () => this.$t("UPDATE_BY"),
          width: 120,
        },
        // 更新时间
        {
          dataIndex: "updateTime",
          title: () => this.$t("UPDATE_TIME"),
          width: 200,
        },
      ];
    },
    // 类型key=>value对象
    typeMap() {
      const obj = {};
      this.queryFormItem.appCode.options.forEach((item) => {
        obj[item.value] = item.label;
      });
      return obj;
    },
  },
  mounted() {
    this.init();
  },
  methods: {
    handChange(val) {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/sys/app-version/get-logo-by-code`,
          {
            params: {
              code: val,
            },
          }
        )
        .then((res) => {
          if (res.data.data === null) {
            const obj = {
              dictCode: "DIC:CORE:PRINT_DESIGN",
              dataValue: val,
            };
            this.$axios
              .get(`${ApiConstant.PREFIX_CORE}/api/sys/dict-data/get-by-code`, {
                params: obj,
              })
              .then((respone) => {
                this.formData.logo = respone.data.data?.dataValueExt1;
                this.formData.appDescribe = respone.data?.data.dataValueExt2;
              });
          } else {
            this.formData.logo = res.data.data?.logo;
            this.formData.appDescribe = res.data?.data.appDescribe;
          }
        });
    },
    formatData(data, status) {
      const result = data.find((item) => item.value === status.toString());
      return result ? result.label : "";
    },
    // 获取选择终端组件返回数据
    getReturnData(selectedRowKeys, selectedRows) {
      this.formData.deviceIds = selectedRows;
    },
    // 查后台分页查询
    searchPageData(data) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/app-version/search`, {
          params: data,
        })
        .then((res) => {
          this.tableData = res.data.data.records;
          this.total = res.data.data.total;
        });
    },
    // 初始化选项
    init() {
      // 获取类型
      this.getDictByCode("DIC:CORE:PRINT_DESIGN").then((res) => {
        this.queryFormItem.appCode.options = res.data.data;
        this.appNameList = res.data.data;
      });

      // 获取状态
      this.getDictByCode("DIC:CORE:APP_STATUS").then((res) => {
        this.stateList = res.data.data;
        this.queryFormItem.status.options = res.data.data;
      });

      this.getDictByCode("DIC:ESOP:BASE_TERMINAL_STATUS").then((res) => {
        this.baseTerminalStatusList = res.data.data;
      });

      this.getDictByCode("DIC:ESOP:BASE_TERMINAL_TYPE").then((res) => {
        this.baseTerminalTypeList = res.data.data;
      });
    },
    // 复制
    handleCopy(row) {
      this.handleOpenDrawer("copy", row);
    },
    // 编辑
    handleEdit(row) {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/sys/app-version/get-by-id/${row.id}`
        )
        .then((res) => {
          const { fileName, fileLength, fileCode, fileUrl, appCode } =
            res.data.data;
          this.fileFormData = {
            name: fileName,
            size: fileLength,
          };
          this.fileCode = fileCode;
          this.fileUrl = fileUrl;
          this.handleOpenDrawer("edit", res.data.data);
        });
    },
    // 新增或者编辑
    handleOpenDrawer(type, row) {
      if (type === "add") {
        this.isUpload = false;
        this.formData.logo = "";
        this.formData.appDescribe = "";
      } else {
        this.isUpload = true;
      }
      this.drawerType = type;
      this.drawer = true;
      if (type === "edit" || type === "copy") {
        this.$set(this, "formData", { ...row });
      } else if (type === "add") {
        this.clearData();
      }
    },
    // 发布
    handleRelease(row) {
      this.$confirm({
        title: this.$t("RELEASE"),
        content: this.$t("RELEASE_INFO"),
        okType: "warning",
        okText: this.$t("RELEASE"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "exclamation-circle",
        onOk: () => {
          this.$axios
            .put(`${ApiConstant.PREFIX_CORE}/api/sys/app-version/${row.id}`)
            .then((res) => {
              this.$message.success(this.$t("RELEASE_SUCCESS"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 下载
    handleDownload(row) {
      if (row?.fileUrl) {
        window.open(fetchFileUrl(row.fileUrl, this));
      }
    },
    handDelete() {
      if (this.selectedRowKeys.length > 0) {
        this.$confirm({
          title: this.$t("DELETE"),
          content: this.$t("DELETE_INFO"),
          okType: "warning",
          okText: this.$t("DELETE"),
          cancelText: this.$t("CANCEL"),
          centered: false,
          icon: "close-circle",
          onOk: () => {
            this.$axios
              .delete(
                `${ApiConstant.PREFIX_CORE}/api/sys/app-version/batch-delete`,
                {
                  params: {
                    ids: this.selectedRowKeys.join(","),
                  },
                }
              )
              .then((res) => {
                this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
                this.$refs.MomTable?.query();
              });
          },
        });
      } else {
        this.$message.error(this.$t("SELECT_ONE_DATA"));
      }
    },
    // 删除
    handleDelete(row) {
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okType: "warning",
        okText: this.$t("DELETE"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.$axios
            .delete(`${ApiConstant.PREFIX_CORE}/api/sys/app-version/${row.id}`)
            .then((res) => {
              this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 保存&修改 防抖
    handleSave() {
      if (this.fileFormData === null) {
        this.$message.warning(`${this.$t("PLEASE_SELECT_FILE_FIRST")}!`);
      } else if (this.isSuccessFile === false) {
        this.save();
      } else {
        this.$axios
          .put(
            `${ApiConstant.PREFIX_CORE}/api/sys/file/merge-chunks/${this.fileFormData.name}/${this.fileFormData.size}`
          )
          .then((respone) => {
            this.fileCode = respone.data.data.fileCode;
            this.fileUrl = respone.data.data.fileUrl;
            this.save();
          });
      }
    },
    save() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          if (this.drawerType === "edit") {
            this.$axios
              .put(`${ApiConstant.PREFIX_CORE}/api/sys/app-version`, {
                ...this.formData,
                fileCode: this.fileCode,
                fileUrl: this.fileUrl,
              })
              .then((res) => {
                this.$message.success(this.$t("EDIT_SUCCESS"));
                this.$refs.MomTable?.query();
                this.drawer = false;
                this.isSuccessFile = false;
              });
          } else {
            this.$axios
              .post(`${ApiConstant.PREFIX_CORE}/api/sys/app-version`, {
                ...this.formData,
                fileCode: this.fileCode,
                fileUrl: this.fileUrl,
              })
              .then((res) => {
                this.$message.success(this.$t("ADD_SUCCESS"));
                this.$refs.MomTable?.query();
                this.drawer = false;
                this.isSuccessFile = false;
              });
          }
        }
      });
    },
    // 对话框取消
    handleCancel() {
      this.$refs.formRef.clearValidate();
      this.$refs.formRef.resetFields();
      this.clearData();
      this.drawer = false;
    },
    // 获取查询条件
    getSearchParams() {
      const req = {
        page: this.page,
        size: this.$store.state.pagination.pageSize,
      };
      return { ...req, ...this.queryForm };
    },
    // 文件上传
    uploadSuccess(file) {
      this.isSuccessFile = true;
      this.fileFormData = file;
    },
    // 清除数据
    clearData() {
      this.$set(this, "formData", {
        appCode: "",
        appVersion: "",
        appVersionName: "",
        deviceIds: [],
        isForce: "Y",
        isAll: "Y",
        fileCode: "",
        fileUrl: "",
        appDescribe: "",
        logo: "",
        remark: "",
      });
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.drawer-footer {
  position: absolute;
  bottom: 80px;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}

/deep/.action-column {
  display: flex;
}
/deep/.logo_disabled {
  width: 100%;
  border: 1px solid #d9d9d9;
  height: 36px;
  padding: 4px 9px;
  display: flex;
  align-items: center;
  background: #f5f5f5;
}
</style>
