<template>
  <div class="layout-container">
    <!-- 菜单栏 -->
    <From :form-items="dynamicFormItems" @formSubmitted="handleFormSubmitted" @formReset="handleFormReset"
      is_add_button="新增" @addForm="edit" />

    <!-- 表格 -->
    <div class="layout-container">
      <Table @getTableData="changeTableData" v-model:page="page" ref="table" :data="tableData"
        @selection-change="handleSelectionChange">
        <el-table-column prop="appId" label="应用ID" width="140" />
        <el-table-column prop="appName" label="应用名称" width="140" />
        <el-table-column prop="superiorName" label="所属应用" width="120" />
        <el-table-column prop="ditchName" label="渠道名称" width="140">
          <template #default="scope">
            <el-tag
              type="success"
              effect="dark"
              v-if="scope.row.ditchName"
            >
              {{ scope.row.ditchName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="nickName" label="所属用户" width="100" />
        <el-table-column prop="appType" label="应用类型" width="100">
          <template #default="scope">
            {{ getDictionaryName("app_type", scope.row.appType) }}
          </template>
        </el-table-column>
        <el-table-column prop="apkUrl" label="下载链接"  width="120">
          <template #default="scope">
            <a v-if="scope.row.apkUrl" :href="scope.row.apkUrl" target="_blank">{{ scope.row.appName }}.apk</a>
          </template>
        </el-table-column>
        <el-table-column prop="qrCode" min-width="130" label="二维码">
          <template #default="scope">
            <el-image v-if="scope.row.qrCode" style="width: 100px; height: 100px;" :z-index="99999" :src="scope.row.qrCode" fit="fill"
              :preview-src-list="[scope.row.qrCode]" preview-teleported="true" />
          </template>
        </el-table-column>
        <el-table-column prop="updateTips" label="更新提示"  width="100" />
        <el-table-column prop="enabled" label="是否启用"  width="100">
          <template #default="scope">
            {{ getDictionaryName("enabled", scope.row.enabled) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <div class="button">
              <el-button class="button-item" type="primary" style="margin-bottom: 5px" @click="edit(scope.row)">
                编辑
              </el-button>
              <el-popconfirm placement="left" title="确认删除该数据?" @confirm="removeApp(scope.row)">
                <template #reference>
                  <el-button class="button-item" style="margin-bottom: 5px" type="warning">删除</el-button>
                </template>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </Table>
    </div>
    <!-- 操作弹窗 -->
    <Layer :layer="layer" @confirm="submit(ruleForm)" @close="layer.show = false">
      <el-form :model="formEdit" :rules="rules" ref="ruleForm" label-width="130px" style="margin-right: 30px">
        <el-row :gutter="5">
          <el-col :span="10">
            <el-form-item label="应用名称：" required prop="appName">
              <el-input v-model="formEdit.appName" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="2"></el-col>
          <el-col :span="10">
            <el-form-item label="应用类型：" prop="appType">
              <el-select v-model="formEdit.appType">
                <el-option :value="1" label="Android" />
                <el-option :value="2" label="IOS" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="10">
            <el-form-item label="出包渠道：" required prop="ditchId">
              <el-select v-model="formEdit.ditchId">
                <el-option v-for="item in ditchListData" :key="item.ditchId" :value="item.ditchId" :label="item.ditchName" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="2"></el-col>
          <el-col :span="10">
            <el-form-item label="所属应用：" required prop="superiorId">
              <el-select v-model="formEdit.superiorId">
                <el-option v-for="item in issuedAppData" :key="item.appId" :value="item.appId" :label="item.appName" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="10">
            <el-form-item label="版本号：" prop="versionCode">
              <el-input v-model="formEdit.versionCode" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="更新提示：" prop="updateTips">
          <el-input v-model="formEdit.updateTips" type="textarea" placeholder="请输入" clearable />
        </el-form-item>
      </el-form>
    </Layer>
  </div>
</template>
<script setup>
import { onBeforeMount, ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import { useGetDictList } from "@/hooks/useGetDictList.js";
import {
  appList,
  saveOrUpdate,
  delApp, issuedApps
} from "@/api/formworkErection.js";
import { ditchList } from '@/api/outBagModule.js'
import From from "@/components/from/index.vue";
import Table from "@/components/table/index.vue";
import Layer from "@/components/layer/index.vue";

const { loadDictData, getDictionaryName } = useGetDictList();
const tableData = ref([]);

// 分页参数, 供table使用
const page = reactive({
  pageNum: 1,
  pageSize: 20,
  total: 0,
});

const formSearch = ref({
  appName: null,
  channelName: null,
  appType: null,
  page: 1, // 当前页码
  limit: 20, // 当前页数量(查询量)
});

const dynamicFormItems = ref([]);

onBeforeMount(() => {
  settingData();
  getList();
  getDitchList();
  getIssuedAppList()
});



// 获取缓存数据设置筛选数据
const settingData = () => {
  loadDictData().then(() => {
    dynamicFormItems.value = [
      {
        label: "应用名称",
        prop: "appName",
        type: "input",
        needEnterEvent: true
      },
      {
        label: "应用类型",
        prop: "appType",
        type: "select",
        options: [
          {
            label: "全部",
            value: null,
          },
          {
            label: "Android",
            value: 1,
          },
          {
            label: "IOS",
            value: 2,
          },
        ],
      },
    ];
  });
};
// 获取出包渠道
const ditchListData = ref([])
const getDitchList = async() => {
  let res = await ditchList({
    page: 1,
    limit: 999,
  })
  ditchListData.value = res.data
}
const issuedAppData = ref([])
const getIssuedAppList = async ()=>{
  let res = await issuedApps({})
  issuedAppData.value = res.data
}

function findByDitchName(ditchId) {
  return ditchListData.value.find(item => item.ditchId === ditchId)
}

// 分页数据
const getList = async () => {
  let res = await appList({ ...formSearch.value });
  tableData.value = res.data;
  page.total = res.pageMeta.total;
};

const changeTableData = () => {
  formSearch.value.page = page.pageNum;
  formSearch.value.limit = page.pageSize;
  // 分页切换
  getList();
};



// 搜索
const handleFormSubmitted = (formData) => {
  console.log("接收到子组件传递的数据", formData);
  formSearch.value.page = 1;
  formSearch.value.limit = 20;
  formSearch.value.channelName = formData?.channelName;
  formSearch.value.appName = formData?.appName;
  formSearch.value.appType = formData?.appType;

  getList();
};

// 表单重置
const handleFormReset = () => {
  formSearch.value = {
    appName: null,
    channelName: null,
    appType: null,
    page: 1, // 当前页码
    limit: 20, // 当前页数量(查询量)
  };
  getList();
};

// 选择监听器
const handleSelectionChange = (val) => {
  context.emit("selection-change", val);
};

// 弹窗
const layer = ref({
  show: false,
  title: "新增App",
  showButton: true,
  width: "60vw",
  edit: false,
});
const formEdit = ref({
  ditchId: null, //渠道ID
  ditchName: '',//渠道名称
  category: "",
  sub_category: "",
  versionCode: "",
  updateTips: "",
  appId: "",
  appName: "",
  qrCode: "",
  apkUrl: "",
  superiorId: '',
});

const edit = (row) => {
  ruleForm.value?.resetFields();
  if (row) {
    layer.value.title = "编辑APP";
    layer.value.edit = true;
    formEdit.value = row;
    formEdit.value.ditchId = Number(row.ditchId)
  } else {
    layer.value.title = "新增APP";
    layer.value.edit = false;
    formEdit.value = {};
  }
  layer.value.show = true;
};

const ruleForm = ref(null);

const rules = reactive({
  ditchId: [
    { required: true, message: "请选择出包渠道", trigger: "change" },
  ],
  superiorId: [
    { required: true, message: "请选择所属应用", trigger: "change" },
  ],
  appName: [
    { required: true, message: "请输入应用名称", trigger: "blur" },
  ],
  appType: [
    { required: true, message: "请输入应用类型", trigger: "blur" },
  ],
  versionCode: [
    { required: true, message: "请输入版本号", trigger: "blur" },
  ],
});

const submit = async (formEl) => {
  await formEl.validate(async (valid, fields) => {
    if (formEdit.value.store_on_sale === 2 && !formEdit.value.store_url && !formEdit.value.store_type) {
      ElMessage.error('上架商店或商店链接不能为空')
      return
    }

    if (valid) {
      let item = findByDitchName(formEdit.value.ditchId)
      formEdit.value.ditchName = item.ditchName
      // 提交内容
      if (layer.value.edit) {
        //api修改需要uuid
        formEdit.value.uuid = formEdit.value.appId;
      }
      const result = await saveOrUpdate({ ...formEdit.value });
      console.log(result)
      if (result.code === 200) {
        if (layer.value.edit) {
          ElMessage.success("修改成功");
          layer.value.show = false;
        } else {
          ElMessage.success("新增成功");
          layer.value.show = false;
        }
        handleFormSubmitted();
      } else {
        ElMessage.error(result.msg);
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 删除
const removeApp = async (row) => {
  await delApp({ appId: row.appId }).then((res) => {
    ElMessage.success("删除成功");
    handleFormSubmitted();
  });
};

</script>

<style scoped lang="scss">
.layout-container {
  .card {
    .title {
      margin-bottom: 10px;
      font-weight: 600;
    }

    display: flex;
    flex-direction: column;
    align-items: start;
    width: calc(100% - 60px);
    margin: 30px 30px 0;
  }

  .button {
    display: flex;
    flex-direction: column;

    .button-item {
      margin: 4px;
    }
  }
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  border: 1px solid #e4e7ed;
}

:deep(.el-image-viewer__wrapper) {
  z-index: 9999 !important;
}
</style>