<script>
import handle from "../../../until/handle";
import axios from "axios";
import {apiMap, baseUrl} from "../../../map/apiMap";
import {rCode} from "../../../map/rcodeMap_esm";
import RoundedTitle from "../../../components/public/roundedTitle.vue";
import copy from "../../../until/copy";
import {isEmpty} from "../../../until/typeTool";
import TableSelect from "../../../components/public/tableSelect.vue";
import dbField_esm from "../../../map/dbField_esm";
import ImageViewer from "../../../components/public/imageViewer.vue";

const productColumns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: '5%',
  },
  {
    title: '产品名称',
    dataIndex: 'name',
    width: '20%',
  },
  {
    title: '产品类型',
    dataIndex: 'type_key',
    width: '20%',
    scopedSlots: {customRender: 'peoType'},
  },
  {
    title: '产品图片',
    dataIndex: 'image',
    width: '20%',
    scopedSlots: {customRender: 'image'},
  },
  {
    title: '操作',
    scopedSlots: {customRender: 'operation'},
    width: '25%',
  },
]
export default {
  name: 'product',
  components: {ImageViewer, TableSelect, RoundedTitle},
  computed: {
    // 产品类型数据
    productTypes(){
      let arr = this.$store.getters.productTypes;
      // 添加 all
      arr.unshift({text: '全部', key: 'all' });
      return arr;
    },
  },
  data(){
    return {
      loading: false,
      productColumns: productColumns,
      productionList: [],
      page: 1,
      pageSize: 10,
      total: 0,
      form: {
        key: {
          val: '',
          oldVal: '',
          init: '',
          msg: '',
          state: 0
        },
        type: {
          val: '',
          init: '',
          msg: '',
          state: 0,
          options: []
        },
      },
      loadErr: false,
    }
  },
  async asyncData(){
    let searchParam = {
      page: 1,
      pageSize: 10,
      key: '',
      type: 'all'
    };
    console.log('搜索产品数据');
    let [err,res] = await handle(axios.get(baseUrl + apiMap.searchProduct.path,{params: searchParam}));
    if(err){
      console.error(err);
      return {};
    }
    let result = res.data;
    if(result.code === rCode.OK){
      return {
        productionList: result.data,
        page: 1,
        pageSize: 10,
        total: result.total,
      }
    }else{
      console.log(`搜索数据失败,${result.msg}`);
      return {}
    }
    return {}
  },
  beforeMount() {
    this.form.type.options = this.productTypes;
    this.form.type.val = this.form.type.options[0].key;
    this.form.type.oldVal = this.form.type.val;
    this.form.type.init = this.form.type.val;
  },
  methods: {
    copy(str){
      copy(str).then(()=>{
        this.$message.success('已经将内容复制到剪切板')
      }).catch(err=>{
        console.error(err.message);
        this.$message.error('内容复制失败,请手动复制内容')
      })
    },
    keyLight(str){
      return str.replace(this.form.key.oldVal,`<span class="text-red-500 text-xl">${this.form.key.oldVal}</span>`)
    },
    // 搜索
    async searchExecute(params = {}){
      let err,res;
      let url = apiMap.searchProduct.path;
      console.log(params);
      // 如果没有传入参数,则使用表单数据
      if(isEmpty(params.key)){
        params.key = this.form.key.oldVal;
      }
      if(isEmpty(params.type)){
        params.type = this.form.type.oldVal;
      }
      params.p = this.page;
      params.l = this.pageSize;
      console.log(`搜索产品数据:${JSON.stringify(params)}`);
      this.loading = true;
      [err,res] = await handle(axios.get(url,{params}));
      this.loading = false;
      if(err){
        return this.$message.error(err.message);
      }
      let result = res.data;
      if(result.code === rCode.OK){
        console.log(`搜索成功`)
        this.form.key.oldVal = params.key;
        this.form.type.oldVal = params.type;
        if (params.p === 1){
          this.$message.success('搜索成功');
          this.total = result.total;
        }
        // 触发更新,设置数据
        this.$nextTick(()=>{
          this.productionList = result.data;
        })


      }else{
        this.$message.error(result.msg);
      }
    },
    // 页码改变
    pageChange(page){
      console.log(`页码改变:${page}`);
      this.page = page;
      console.log(this.page);
      this.searchExecute();
    },
    // 页数改变
    pageSizeChange(pageSize){
      console.log('页数改变');
      this.pageSize = pageSize;
      this.searchExecute();
    },
    onSearchHandle(){
      this.page = 1;
      console.log(this.form.type.val);
      this.searchExecute({
        key: this.form.key.val,
        type: this.form.type.val,
      });
    },
    refreshHandel(){
      this.page = 1;
      this.searchExecute();
    },
    getProTypeText(key){
      let type = this.productTypes.find(item=>item.key === key);
      return type ? type.text : '';
    },

  }
}
</script>

<template>
  <div class="w-full p-2">
    <rounded-title class="text-xl">
      <span>产品管理,产品中心</span>
      <a href="/manger/product/type" class="px-10 h-full ml-5 rounded bg-blue-400 text-white cursor-pointer hover:text-orange-500 ">产品分类管理</a>
    </rounded-title>

    <div class="w-full rounded border mt-2 bg-white p-2">
      <div class="w-full flex h-14 items-center justify-between border-b">

        <div class="flex">
          <table-select
            class="w-48 !mx-3 flex-shrink-0"
            :options="form.type.options"
            v-model="form.type.val"
          />
          <a-input-search class="!ml-2 w-64" type="text" allow-clear placeholder="产品关键字"
                          @search="onSearchHandle"
                          :loading="loading" v-model="form.key.val" />
        </div>


        <div class="flex">
          <a-button class="ml-2" type="primary" @click="refreshHandel" :loading="loading">刷新</a-button>
        </div>

      </div>
      <div class="w-full">
        <a-table
          :columns="productColumns"
          :loading="loading"
          :row-key="record => record.id"
          :pagination="false"
          :data-source="productionList"
        >
          <template slot="proType" slot-scope="text">
            <span>{{getProTypeText(text)}}</span>
          </template>

          <template slot="image" slot-scope="text,record">
            <image-viewer :src="text" :alt="record.name" />
          </template>

          <template slot="keyLight" class="flex" slot-scope="text">
            <div class="w-full flex items-center">
              <div  v-html="keyLight(text)"></div>
              <svg-icon :name="'copy'" :icon-class="'copy'" class="text-2xl cursor-pointer mx-2" title="点击复制" @click.native="copy(text)" />
            </div>
          </template>
          <template class="flex justify-center" slot="operation" slot-scope="text,record">
            <a-button  type="primary">
              <a :href="`/manger/product/info?id=${record.id}`">产品详情</a>
            </a-button>

            <a-button class="mx-3" type="primary">
              <a :href="`/manger/product/edit?id=${record.id}`">编辑产品</a>
            </a-button>

          </template>

        </a-table>
        <a-pagination
          class="mt-2"
          :total="total"
          :page-size="pageSize"
          :current="page"
          @change="pageChange"
          @show-size-change="pageSizeChange"
          />
      </div>
    </div>
  </div>
</template>

<style scoped>

</style>
