<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.product_name"
        placeholder="商品名称"
        style="width: 200px; margin-right: 10px"
        class="filter-item"
      />
      <el-input
        v-model="listQuery.third_product_id"
        placeholder="平台商品ID"
        style="width: 200px; margin-right: 10px"
        class="filter-item"
      />
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="getList"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px"
        type="primary"
        icon="el-icon-circle-plus"
        @click="handleCreate('add', [])"
      >
        新增商品
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column align="center" label="操作" width="200">
        <template slot-scope="scope">
          <el-button
            type="primary"
            @click="handleCreate('edit', scope.row)"
            size="small"
            icon="el-icon-edit"
          >
            修改
          </el-button>

          <el-button
            type="primary"
            v-if="scope.row.status"
            @click="onWork(scope.row.id)"
            size="small"
            icon="el-icon-date"
          >
            班期
          </el-button>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        label="商品名称"
        prop="product_name"
      ></el-table-column>

      <el-table-column
        align="center"
        label="所属平台"
        width="160"
        prop="os_name"
      ></el-table-column>

      <el-table-column
        align="center"
        label="平台商品ID"
        width="200"
        prop="third_product_id"
      ></el-table-column>

      <el-table-column align="type" label="境内/境外" width="100" prop="type">
        <template slot-scope="scope">
          <span>{{ scope.row.type === 1 ? "境内" : "境外" }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="type"
        label="天数"
        width="120"
        prop="day"
      >
      <template slot-scope="scope">
        <span>{{ scope.row.day }}天{{ scope.row.night }}晚</span>
      </template>
    </el-table-column>
      <!-- <el-table-column
        align="type"
        label="详细行程"
        width="180"
        prop="trip_info"
      >
        <template slot-scope="scope">
          <span class="link-type" @click="openLink(scope.row.trip_info)">{{
            scope.row.trip_info
          }}</span>
        </template>
      </el-table-column> -->

      <el-table-column width="180px" align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{
            scope.row.created_at | parseTime("{y}-{m}-{d} {h}:{i}")
          }}</span>
        </template>
      </el-table-column>

      <el-table-column width="180px" align="center" label="修改时间">
        <template slot-scope="scope">
          <span>{{
            scope.row.updated_at | parseTime("{y}-{m}-{d} {h}:{i}")
          }}</span>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <!-- 添加/编辑表单 -->
    <el-dialog
      :visible.sync="dialogVisible"
      @open="onOpen"
      @close="onClose"
      :title="dialogTitle"
    >
      <el-form
        ref="elForm"
        :model="formData"
        :rules="rules"
        size="medium"
        label-width="120px"
      >
        <el-form-item label="请选择平台" prop="os">
          <el-select v-model="formData.os" placeholder="请选择平台" clearable>
            <el-option
              v-for="(item, index) in ossArr"
              :key="item.id"
              :label="item.os"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品名称" prop="product_name">
          <el-input
            v-model="formData.product_name"
            placeholder="请输入产品名称"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item label="第三方产品编号" prop="third_product_id">
          <el-input
            v-model="formData.third_product_id"
            placeholder="请输入第三方产品编号"
            clearable
          >
          </el-input>
        </el-form-item>
        <el-form-item label="天数" prop="day">
          <el-input v-model="formData.day" placeholder="请输入天数" clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="晚数" prop="night">
          <el-input v-model="formData.night" placeholder="请输入晚数" clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="出游类型" prop="type">
          <el-radio-group v-model="formData.type" size="medium">
            <el-radio
              v-for="(item, index) in fieldTypeOptions"
              :key="item.value"
              :label="item.value"
              >{{ item.label }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="详细行程" prop="trip_info" required>
          <el-upload
            ref="field105"
            action=""
            :before-upload="wordBeforeUpload"
            :http-request="handlesAvatarSuccess"
            :on-success="handleWordSuccess"
            :on-error="handleUploadError"
            :on-remove="handleRemove"
            :on-change="handleChange"
            :before-remove="beforeRemove"
            :limit="1"
            :file-list="fieldFileList"
            accept=".pdf,.docx,.xlsx"
          >
            <el-button size="small" type="primary" icon="el-icon-upload"
              >点击上传</el-button
            >
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="handelConfirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from "@/components/Pagination";
import { getProductsListsApi, postAddProductApi } from "@/api/admin";
import { getToken } from "@/utils/auth";
export default {
  name: "ProManagement",
  components: { Pagination },
  data() {
    return {
      listQuery: {
        page: 1,
        limit: 10,
      },
      total: 0,
      listLoading: true,
      list: [],
      ossArr: [],
      dialogVisible: false,
      dialogTitle: "新增商品",
      fieldFileList: [],
      formData: {
        os: "",
        product_name: "",
        type: "",
        day: "",
        night: "",
        third_product_id: "",
        trip_info: "",
      },
      fieldAction: process.env.VUE_APP_BASE_API + "/admin/upload/index",
      fieldTypeOptions: [
        {
          label: "境内",
          value: 1,
        },
        {
          label: "境外",
          value: 2,
        },
      ],
      rules: {
        os: [
          {
            required: true,
            message: "请选择平台",
            trigger: "change",
          },
        ],
        product_name: [
          {
            required: true,
            message: "请输入线路名称",
            trigger: "blur",
          },
        ],
        day: [
          {
            required: true,
            message: "请输入天数",
            trigger: "blur",
          },
        ],
        night: [
          {
            required: true,
            message: "请输入晚数",
            trigger: "blur",
          },
        ],
        third_product_id: [
          {
            required: true,
            message: "请输入第三方产品编号",
            trigger: "blur",
          },
        ],
        type: [
          {
            required: true,
            message: "请选择出游类型",
            trigger: "change",
          },
        ],
      },
      editType: "",
    };
  },
  created() {
    this.getList();
  },
  methods: {
    handleCreate(type, item) {
      this.editType = type;
      type === "add" ? this.AddProduct() : this.editProduct(item);
    },
    AddProduct() {
      this.dialogTitle = "新增商品";
      this.dialogVisible = true;
    },
    editProduct(row) {
      console.log(row, "row");
      this.formData = { ...row };
      this.dialogTitle = "编辑商品";
      this.dialogVisible = true;
    },
    async getList() {
      console.log("this.listQuery", this.listQuery);
      const res = await getProductsListsApi(this.listQuery);
      if (res.error === 0) {
        this.listLoading = false;
        this.total = res.data.total;
        this.list = res.data.data;
        this.ossArr = res.ext.oss;
      }
    },
    onWork(id) {
      this.$router.push(`/system/proScheduling?id=${id}`);
    },
    handleChange(file, fileList) {
      this.fileList = fileList.slice(-1);
    },
    async handlesAvatarSuccess(file) {
      try {
        var formdata = new FormData();
        formdata.append("file", file.file);
        const res = await this.$axios.post("/admin/upload/index", formdata, {
          headers: {
            "Content-type": "multipart/form-data",
            "X-Token": getToken(),
          },
        });
        console.log(res, "收拾收拾");
        if (res.error === 0) {
          file.onSuccess(res);
        }
      } catch (error) {
        console.log(file, "error--handlesAvatarSuccess");
        let uid = file.file.uid;
        let idx = this.$refs.field105.uploadFiles.findIndex(
          (item) => item.uid === uid
        );
        this.$refs.field105.uploadFiles.splice(idx, 1);
        this.$message.error(`上传失败`);
      }
    },
    handleWordSuccess(res, file, fileList, index) {
      console.log(res, file, fileList, "成功了");
      if (res) {
        // this.formData.trip_info = fileList
        //   .map((item) => item.url || item.response.url)
        //   .join(",");
        this.formData.trip_info = `${window.location.protocol}//${window.location.host}${res.data}`;
        this.fieldFileList = [
          {
            name: file.name,
            uid: file.uid,
            url: this.formData.trip_info,
          },
        ];
        this.$message.success("上传成功");
      }
      // if (!res) return;

      // this.formData.trip_info = `${window.location.protocol}//${window.location.host}${res.data}`;
      // this.fieldFileList = [
      //   {
      //     name: file.name,
      //     uid: file.uid,
      //     url: this.formData.trip_info,
      //   },
      // ];
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleRemove(file, fileList) {
      console.log(file, fileList, "handleRemove");
      this.formData.trip_info = "";
      this.fieldFileList.map((item, index) => {
        if (item.uid === file.uid) {
          this.fieldFileList.splice(index, 1);
        }
      });
    },
    handleUploadError(err, file) {
      this.$message.error(`上传失败: ${file.name}`);
      console.log(this.fieldFileList, "失败了");
      this.fieldFileList.map((item, index) => {
        if (item.uid === file.uid) {
          this.fieldFileList.splice(index, 1);
        }
      });
    },
    wordBeforeUpload(file) {
      const isRightType = [
        "application/pdf",
        "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      ].includes(file.type);
      const isRightSize = file.size / 1024 / 1024 < 2;

      if (!isRightType) {
        this.$message.error("只允许上传 PDF、DOCX、XLSX 格式的文件");
      }
      if (!isRightSize) {
        this.$message.error("文件大小超过 2MB");
      }

      return isRightType && isRightSize;
    },
    openLink(link) {
      window.open(link);
    },
    onOpen() {},
    onClose() {
      this.$refs["elForm"].resetFields();
      this.$refs.field105.uploadFiles = []; // 删除该条数据
    },
    close() {
      console.log("1111", this.$refs.field105.uploadFiles);
      this.dialogVisible = false;
      this.$refs.field105.uploadFiles = []; // 删除该条数据
    },
    handelConfirm() {
      this.$refs["elForm"].validate(async (valid) => {
        if (!valid) return;
        const res = await postAddProductApi(this.formData);
        if (res.error === 0) {
          this.getList();
          this.$message({
            message: this.editType === "add" ? "商品添加成功" : "商品编辑成功",
            type: "success",
          });
        }
        this.close();
      });
    },
  },
};
</script>
<style scoped lang="scss">
.link-type {
  color: rgb(7, 181, 249);
  cursor: pointer;
}
</style>
