<template>
  <div>
    <!-- 新增互动视频基本信息 -->
    <el-dialog
      :title="dialogTitle"
      v-model="materialOpen"
      width="1200"
      append-to-body
    >
      <el-form
        :model="form"
        ref="dataForm"
        :rules="rules"
        label-width="110px"
        inline
      >
        <el-row :gutter="10">
          <el-col :span="8">
            <el-form-item label="互动视频名称" prop="interactionName">
              <el-input
                v-model="form.interactionName"
                placeholder="请输入互动视频名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="节点类型" prop="nodeType">
              <el-select v-model="form.nodeType" placeholder="请选择节点类型">
                <el-option label="根节点" value="root-node" />
                <el-option label="场景节点" value="plot-node" />
                <el-option label="跳转节点" value="jump-node" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="素材" prop="selectMaterial">
              <el-radio-group v-model="form.selectMaterial">
                <el-radio :label="1">选择已有素材</el-radio>
                <el-radio :label="2" @click="uploadSource">上传素材</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-show="form.selectMaterial == 1">
            <el-form-item label="">
              <!-- 列表 -->
              <el-table
                border
                row-key="materialId"
                v-loading="loading"
                :data="libraryList"
                @selection-change="handleSelectionChange"
              >
                <el-table-column
                  type="selection"
                  width="100"
                  align="center"
                  :reserve-selection="true"
                />
                <el-table-column
                  type="index"
                  label="序号"
                  width="100"
                  align="center"
                />
                <el-table-column
                  prop="materialName"
                  label="素材名称"
                  align="center"
                />
                <!-- 素材类型,0-视频、1-图片 -->
                <el-table-column
                  prop="materialType"
                  label="素材类型"
                  align="center"
                >
                  <template #default="{ row }">
                    {{ libraryType[row.materialType] }}
                  </template>
                </el-table-column>
                <!-- 0=未发布,1=发布 -->
                <el-table-column prop="status" label="状态" align="center">
                  <template #default="{ row }">
                    {{ libraryStatus[row.status] }}
                  </template>
                </el-table-column>
              </el-table>
              <pagination
                v-show="total > 0"
                :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            :loading="confirmLoading"
            @click="dialogSubmit"
            >确 定</el-button
          >
          <el-button :loading="confirmLoading" @click="dialogCancel"
            >取 消</el-button
          >
        </div>
      </template>
    </el-dialog>

    <el-dialog title="新增素材" v-model="addSourceOpen" width="800">
      <el-form
        :model="materialForm"
        ref="materialFormRef"
        :rules="materialRules"
        label-width="100"
      >
        <el-form-item label="素材名称" prop="materialName">
          <el-input
            v-model="materialForm.materialName"
            placeholder="请输入素材名称"
          />
        </el-form-item>
        <el-form-item label="素材类型" prop="materialType">
          <el-select
            v-model="materialForm.materialType"
            placeholder="请选择素材类型"
          >
            <el-option :value="0" label="视频" />
            <el-option :value="1" label="图片" />
          </el-select>
        </el-form-item>
        <el-form-item label="素材文件">
          <el-upload
            ref="uploadRef"
            action=""
            :file-list="materialForm.fileList"
            :on-change="uploadChange"
            :on-remove="uploadRemove"
            :auto-upload="false"
            :limit="1"
          >
            <template #trigger>
              <el-button type="primary">选择文件</el-button>
            </template>
            <template #tip>
              <div class="el-upload__tip">仅支持上传图片或视频文件</div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            :loading="materialConfirmLoading"
            @click="sourceAdd"
            >确 定</el-button
          >
          <el-button :loading="materialConfirmLoading" @click="sourceAddCancel"
            >取 消</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="FormFields">
import {
  getLibraryList,
  libraryAdd,
} from "@/api/interactVideo/sourceMaterialManage";
import { interactionVideoAdd } from "@/api/interactVideo/videoManage";
const { proxy } = getCurrentInstance();
const router = useRouter();
const props = defineProps({
  open: {
    type: Boolean,
    default: false,
  },
});
const emits = defineEmits(["close"]);
const materialOpen = ref(false);
const dialogTitle = ref("新增互动视频");
const confirmLoading = ref(false);
const loading = ref(false);
const libraryList = ref([]);
const total = ref(0);
const materialConfirmLoading = ref(false);
const addSourceOpen = ref(false);
const ids = ref([]);
const uploadId = ref([]);
const data = reactive({
  form: {
    nodeType: "root-node",
    selectMaterial: 1,
  },
  rules: {
    interactionName: [
      { required: true, message: "互动视频名称不能为空", trigger: "blur" },
    ],
  },
  materialForm: {
    materialName: undefined,
    materialType: undefined,
    fileList: [],
  },
  materialRules: {
    materialName: [
      { required: true, message: "素材名称不能为空", trigger: "blur" },
    ],
    materialType: [
      { required: true, message: "素材类型不能为空", trigger: "change" },
    ],
  },
  libraryType: {
    0: "视频",
    1: "图片",
  },
  libraryStatus: {
    0: "未发布",
    1: "已发布",
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
});

const {
  form,
  rules,
  libraryType,
  libraryStatus,
  queryParams,
  materialRules,
  materialForm,
} = toRefs(data);

watchEffect(() => {
  if (props.open) {
    materialOpen.value = true;
    getList();
  } else {
    materialOpen.value = false;
  }
});

// 互动视频新增并关联素材
function dialogSubmit() {
  proxy.$refs["dataForm"].validate((valid) => {
    if (valid) {
      // 判断选中素材id和上传素材id是否为空
      if (ids.value.length == 0 && uploadId.value.length == 0) {
        proxy.$modal.msgError("请选择素材");
        return;
      }
      confirmLoading.value = true;
      const { interactionName, remark, nodeType } = form.value;
      const params = {
        materialIds: ids.value,
        interactionName,
        remark,
        nodeType,
      };
      interactionVideoAdd(params)
        .then((res) => {
          // 新增成功后拿到id跳转互动视频节点编辑
          if (res.code == 200) {
            proxy.$modal.msgSuccess("新增成功");
            dialogCancel();
            router.push({
              path: "/interactVideo/videoOperation",
              query: { interactionId: res.data },
            });
          }
        })
        .finally(() => {
          confirmLoading.value = false;
        });
      confirmLoading.value = true;
    }
  });
}
function dialogCancel() {
  emits("close", false);
  confirmLoading.value = false;
}

/** 查询素材列表 */
function getList() {
  loading.value = true;
  getLibraryList(queryParams.value).then((response) => {
    libraryList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}
// 选中素材id
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.materialId);
}

// 素材新增
function uploadSource() {
  addSourceOpen.value = true;
  materialForm.value = {
    materialName: undefined,
    materialType: 0,
    fileList: [],
  };
}
function sourceAdd() {
  const formData = new FormData();
  proxy.$refs["materialFormRef"].validate((valid) => {
    if (valid) {
      materialConfirmLoading.value = true;
      const { materialName, materialType, fileList } = materialForm.value;
      formData.append("materialName", materialName);
      formData.append("materialType", materialType);
      fileList.forEach((file) => {
        formData.append("file", file.raw);
      });
      libraryAdd(formData)
        .then((res) => {
          if (res.code == 200) {
            proxy.$modal.msgSuccess("新增成功");
            uploadId.value.push(res.data);
            addSourceOpen.value = false;
          }
        })
        .finally(() => {
          materialConfirmLoading.value = false;
        })
        .catch((err) => {
          console.log(err);
        });
    }
  });
}
// 取消素材新增
function sourceAddCancel() {
  materialConfirmLoading.value = false;
  addSourceOpen.value = false;
}

// 文件上传回调
function uploadChange(file) {
  materialForm.value.fileList.push(file);
}

function uploadRemove() {
  materialForm.value.fileList = [];
}
</script>
