<template>
  <el-main class="bg_white" style="min-height: calc( 100% - 80px )">
    <!--顶部搜索-->
    <CommonSeach class="comSeach" v-model:diySerach="data.diySerach" @getSeachData="getSeachData" @getChangeValue="getChangeValue"></CommonSeach>
    <el-row class="title_box-1">
      <el-col :span="24">
        <!-- :disabled="data.language_id !== 1" -->
        <!-- :disabled="data.language_id !== 1" -->
        <el-button type="primary" @click="handleEdit('', 'add')">新增品牌</el-button>
        <el-button type="primary" @click="handleDel()" >删除品牌
        </el-button>
      </el-col>
    </el-row>
    <!---产品列表-->
    <div class="table">
      <el-table :data="data.list" border fit highlight-current-row @selection-change="handleSelectionChange">
        <el-table-column align="center" type="selection" width="55" />
        <el-table-column align="center" prop="id" label="ID" width="95"></el-table-column>
        <el-table-column label="品牌图标" prop="icon" align="center" width="360">
          <template #default="scope">
            <img :src="scope.row.icon ? scope.row.icon : defaulImg" @error="e => {e.target.src = defaulImg}"
              style="width:40px;height:40px;" />
          </template>
        </el-table-column>
        <el-table-column label="品牌名称" prop="name"></el-table-column>
        <el-table-column label="创建时间" prop="create_time"></el-table-column>
        <el-table-column label="状态" align="center" width="150">
          <template #default="scope">
            <el-switch v-model="scope.row.status" class="ml-2" :active-value=1 :inactive-value=0
              @change="changeStatus(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column fixed="right" width="150" label="操作" prop="" align="center">
          <template #default="scope">
            <el-button title="编辑" type="text" @click="handleEdit(scope.row, 'edit')">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="m-b-20 m-t-20" :current-page="query_form.page" :page-sizes="[10, 20, 30]"
        :page-size="query_form.size" layout="total, sizes, prev, pager, next, jumper" :total="data.count"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" small>
      </el-pagination>
    </div>
    <!--图片放大弹窗-->
    <el-dialog v-model="data.dialogVisible">
      <el-image width="100%" :src="data.dialogImg" alt></el-image>
    </el-dialog>
    <!--新增分类-->
    <el-dialog v-model="data.editCate" :show-close="true" :title="data.dialogTit" width="440px" center>
      <el-form ref="edit_form" :model="data.edit_form" label-width="80px" :rules="data.rules">
        <el-form-item label="品牌名称" prop="name" required>
          <el-input v-model="data.edit_form.name" maxlength="100" style="width: 80%;" />
        </el-form-item>
        <el-form-item label="品牌图标">
          <el-upload ref="upload" v-model:file-list="data.defaultImg" :action="data.api_upload_url"
            list-type="picture-card" :with-credentials="true" name="images" :data="data.icon"
            :on-success="function (res, file, file_list) {return handleSuccess(res, file, file_list, data.edit_form)}"
            :on-preview="handlePreview" :limit="data.limit"
            :on-remove="function (file, file_list) {return handleRemove(file, file_list,  data.edit_form)}"
            accept=".jpg,.png" :on-exceed="onexceed">
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelClick">取消</el-button>
          <el-button type="primary" @click="comfirmClick">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!--删除提醒-->
    <el-dialog v-model="data.deleteModal" title="删除品牌" :show-close="true" width="440px">
      <div class="del_text">确定删除已选择的品牌吗？</div>
      <template #footer>
        <div class="text-r">
          <el-button type="primary" plain @click="cancel">取消</el-button>
          <el-button type="primary" @click="deleteClick">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </el-main>
</template>
<script>
import CommonSeach from '@/views/components/CommonSeach/CommonSeach.vue'
import { reactive, onMounted, computed, ref, onActivated } from 'vue'
import Request from '@/utils/request.js'
import { ElMessage } from 'element-plus'
import defaulImg from '@/assets/defaulImg.jpg'
import { useStore } from 'vuex'
export default {
  name: 'Brand',
  components: {
    CommonSeach
  },
  setup () {
    const data = reactive({
      diySerach:[],
      cdn: '',
      icon: {
        type: 'images',
        language_id: 1,
      },
      row: {},
      language_id: 0,
      sels: [], //当前选框选中的值
      multipleSelection: [],
      limit: 1,
      defaultImg: [],
      dialogVisible: false,
      deleteModal: false,
      dialogImg: '',
      dialogTit: '',
      api_upload_url: process.env.VUE_APP_API_BASEURL + "admin/v1/brand/upload",
      count: 0,
      editCate: false,
      list: [],
      isDisabled: false,
      edit_form: {
        name: '',
        icon: '',
        id: '',
        language_id: 1,
      },
      //验证规则
      rules: {
        name: [{ type: 'string', required: true, message: "请填写品牌名称", trigger: 'blur' }, { max: 100, message: "名称长度不能超过100位" }]
      },
      lockClear: false
    })
    const query_form = reactive({
      page: 1,
      size: 10,
      name:''
    })
    let store = useStore()
    onMounted(() => {
      store.state.leftAside.isShowLanguage = false
      data.cdn = store.state.user.cdn
      data.language_id = store.state.user.language.id
      data.icon.language_id = store.state.user.language.id
      data.diySerach = [
        [
          { label: '品牌名称', value: '', placeholder: '请输入品牌名称', type: 'ipt', queryValue: 'name' },
          { type: 'searchReset', url: 'v1/brand', otherValue: { page: query_form.page, size: query_form.size } },
          { type: 'spec' },
          { type: 'spec' },
          { type: 'spec' },
        ]
      ]
      getList()
    })
    onActivated(() => {
      store.state.leftAside.isShowLanguage = false
    })
    //实例化请求
    const request = new Request()
    const getList = () => {
      data.list = []
      request.get('v1/brand', query_form).then(res => {
        if (res.status == 200) {
          data.list = res.data.data
          data.count = res.data.count
          data.list.forEach(item => {
            if (item.icon != '') {
              // item.icon = data.cdn + item.icon
              item.uid = item.id
              // item.show_img = [
              //   {
              //     uid: item.id,
              //     url: item.icon
              //   }
              // ]
            }
          })
        } else {
          ElMessage({
            type: 'error',
            message: res.message
          })
        }
      })
    }
    const handleSizeChange = (size) => {
      // console.log(query_form)
      query_form.size = size
      getList()
    }

    const handleCurrentChange = (page) => {
      // console.log(query_form)
      query_form.page = page
      getList()
    }

    //编辑
    // const handleEdit = (row) => {
    //   data.row = row
    //   data.edit_form = row
    //   data.editCate = true
    // }
    //修改状态
    const changeStatus = (row) => {
      // console.log(row)
      let query = {
        id: row.id,
        status: row.status
      }
      // console.log(row)
      request.post('v1/brand/change_status', query).then(res => {
        if (res.status == 200) {
          ElMessage({
            type: 'success',
            message: res.message
          })
        } else {
          setTimeout(() => {
            getList()
          }, 200)
        }
      })
    }
    const handlePreview = (file) => {
      data.dialogImg = file.url
      data.dialogVisible = true
    }
    const handleSuccess = (res, file, fileList, item) => {
      data.edit_form.icon = res.data[0].r_path
      data.lockClear = false
      // item.icon = res.data[0].url
      // comfirmClick(item)
    }
    const handleRemove = (file, file_list, item) => {
      data.defaultImg = []
      data.lockClear = true
    }
    const onexceed = (file, fileList) => {
      // console.log(file, fileList)
      if (fileList.length + file.length > data.limit) {
        ElMessage({
          type: 'error',
          message: '最多可上传1张品牌图标!'
        })
        return false
      }
    }
    //编辑确认
    // const comfirmClick = (item) => {
    //   request.put('v1/brand/' + item.id, { id: item.id, icon: item.icon, status: item.status }).then(res => {
    //     if (res.status == 200) {
    //       ElMessage({
    //         type: 'success',
    //         message: res.message
    //       })
    //       getList()
    //     } else {
    //       ElMessage({
    //         type: 'error',
    //         message: res.message
    //       })
    //     }
    //   })
    // }
    //取消
    const cancel = () => {
      data.deleteModal = false
      clearData()
    }
    // 勾选
    const handleSelectionChange = (rows) => {
      data.multipleSelection = rows
    }
    //新增/编辑分类
    const handleEdit = (row, type) => {
      clearData()
      data.defaultImg = []
      // console.log(type)
      if (type == 'edit') {
        data.type = 'edit'
        data.dialogTit = '编辑品牌'
        data.edit_form.id = row.id
        data.edit_form.language_id = row.language_id
        data.edit_form.name = row.name
        data.edit_form.icon = row.icon
        row.icon ? data.defaultImg = [{ name: row.name, url: row.icon }] : data.defaultImg = []
        data.isDisabled = true
      } else {
        data.type = 'add'
        data.dialogTit = '添加品牌'
        data.isDisabled = false
      }
      data.editCate = true
    }
    const cancelClick = () => {
      data.editCate = false
    }
    //删除
    const handleDel = () => {
      let newStr = ''
      if (data.multipleSelection.length > 0) {
        data.multipleSelection.forEach(el => {
          if (el.id) {
            newStr += el.id + ','
          }
        });
        if (newStr.charAt(newStr.length - 1) == ',') {
          // console.log('inner')
          newStr = newStr.slice(0, newStr.length - 1)
        }
        data.row.id = newStr
        // console.log(newStr)
        // console.log(data.row.id)
        data.deleteModal = true
      } else {
        ElMessage({
          type: 'error',
          message: '请先勾选需要删除的品牌'
        })
      }

    }
    // 获取搜索、重置数据并更新
    const getSeachData = (value) => {
      // console.log('value',value)
      data.list = value.data
      data.count = value.count
    }
    // 输入的搜索框发生改变
    const getChangeValue = (value) => {
      // console.log('getChangeValue - value',value)
      query_form[value.queryValue] = value.value
    }
    const deleteClick = () => {
      request.post('v1/brand/delete/' + data.row.id, { id: data.row.id }).then(res => {
        if (res.status == 200) {
          data.deleteModal = false
          ElMessage({
            type: 'success',
            message: res.message
          })
          getList()
        }
      })
    }
    //确认修改
    const comfirmClick = () => {
      // console.log('click comfirm edit_form', data.edit_form)
      // console.log('click comfirm value', data.value)
      if (data.type == 'edit') {
        if (typeof data.edit_form.icon == 'string') {
          data.edit_form.icon = 'dev_api_product' + data.edit_form.icon.split('dev_api_product')[1]
        } else {
          data.edit_form.icon = 'dev_api_product' + data.edit_form.icon[0].url.split('dev_api_product')[1]
        }
        if (data.lockClear) {
          data.edit_form.icon = ''
        }
        request.put('v1/brand/' + data.edit_form.id, data.edit_form).then(res => {
          if (res.status == 200) {
            data.editCate = false
            getList()
            ElMessage({
              type: 'success',
              message: res.message
            })
          } else {
            ElMessage({
              type: 'error',
              message: res.message
            })
            data.edit_form.status = (!data.edit_form.status) == true ? 1 : 0
          }
        })
      } else {
        data.edit_form.id = ''
        data.edit_form.language_id = data.language_id
        data.edit_form.value = data.value
        request.post('v1/brand', data.edit_form).then(res => {
          if (res.status == 200) {
            data.editCate = false
            getList()
            ElMessage({
              type: 'success',
              message: res.message
            })
          } else {
            ElMessage({
              type: 'error',
              message: res.message
            })
          }
        })
      }
    }
    //清除表单数据
    const clearData = () => {
      data.value = ''
      data.edit_form = {
        name: '',
        icon: '',
        id: '',
      }
    }
    return {
      data,
      query_form,
      getList,
      handleSizeChange,
      handleCurrentChange,
      handleSelectionChange,
      handleEdit,
      handleDel,
      deleteClick,
      cancelClick,
      changeStatus,
      comfirmClick,
      cancel,
      clearData,
      handlePreview,
      handleSuccess,
      handleRemove,
      onexceed,
      defaulImg,
      getSeachData,
      getChangeValue
    }
  }
}
</script>
<style scoped>
.title_box-1{
  margin: 0px 24px 0 24px;
}
::v-deep(.el-upload) {
  position: relative;
}
.el-icon-plus {
  position: absolute;
  width: 28px;
  height: 28px;
  top: calc(50% - 14px);
  left: calc(50% - 14px);
}
::v-deep(.el-upload--picture-card),
::v-deep(.el-upload-list--picture-card .el-upload-list__item),
::v-deep(.el-upload-list--picture-card .el-upload-list__item-actions) {
  width: 60px !important;
  height: 60px !important;
}
::v-deep(.el-upload-list--picture-card) {
  --el-upload-list-picture-card-size: 60px;
}
::v-deep(.el-dialog__footer) {
  text-align: right;
}
::v-deep(.comSeach .el-form-item__label) {
  text-align: left!important;
  padding-left: 22px!important;
}
</style>