/**
  // author：zhangb
  // time:2022-11-07
  // desc:牛只分类管理
*/
<template>
  <div class="classifyManage">
    <!-- top -->
    <div>
      <Row>
        <Col span="24" style="text-align:right;">
          <Button type="primary" @click="addNewClassify">添加一级分类</Button>
        </Col>
      </Row>
    </div>

    <!-- tree content -->
    <div class="tree_content">
      <el-tree :data="dataSource" show-checkbox node-key="typeId" :props="classifyTreePropsSet" :expand-on-click-node="false" style="width:90%;">
        <template #default="{ node, data }">
          <div class="custom-tree-node">
            <span>{{ node.data.name }}</span>
            <span>输出顺序：{{node.data.sort || '暂无'}}</span>
            <span style="text-align:right !important;">
              <a v-show="node.level < 3" @click="addNextClassify(node,data)">添加下级分类</a>
              <a v-show="node.level === 3" @click="optClassifyImg(node,data)">分类图片</a>
              <a style="margin-left: 8px" @click="editTreeClassify(node,data)">编辑</a>
              <a style="margin-left: 8px" @click="delClassidy(node,data)">删除</a>
            </span>
          </div>
        </template>
      </el-tree>
    </div>

    <!-- 新增分类信息 -->
    <Modal v-model="optClassifyModal" :title="optClassifyModalTitle" width="30%">
      <Tag v-show="optClassifyModalTitle == '添加下级分类'" color="primary" size="medium" style="margin-bottom:1em;">
        当前上级：{{recordClassifyData.name}}
      </Tag>
      <Form ref="optClassifyFormRef" :model="optClassifyForm" :rules="optClassifyRule" :label-width="100">
        <FormItem prop="name" label="分类名称：">
          <Input v-model="optClassifyForm.name" placeholder="新增分类名称" style="width:80%;"></Input>
        </FormItem>
        <FormItem prop="sort" label="输出排序：">
          <InputNumber :min="1" v-model="optClassifyForm.sort" placeholder="请输入输出顺序" style="width:80%;" />
        </FormItem>
      </Form>
      <template #footer>
        <div style="text-align:center;">
          <Button style="margin-right:5em;" @click="optClassifyModal = false">取消操作</Button>
          <Button type="primary" @click="submitOptClassify">确定提交</Button>
        </div>
      </template>
    </Modal>

    <!-- 三级分类显示图片 -->
    <Modal v-model="optClassifyImgModal" :title="optClassifyModalTitle" width="30%">
      <Tag color="primary" size="medium" style="margin-bottom:1em;">
        当前分类：{{recordClassifyData.name}}
      </Tag>

      <div style="margin-left:1rem;">
        <div style="margin:.5rem 0;">分类图片</div>
        <Upload
          type="drag"
          :action="uploadUrl"
          :headers="{'X-AIYANGNIU-SIGNATURE':token}"
          :show-upload-list="false"
          :on-success="handleSuccess"
          :before-upload="handleBeforeUpload"
          :format="['jpg','jpeg','png']"
          :max-size="2048"
          :on-format-error="handleFormatError"
          style="width:100px; height:100px;">
          <div v-if="!recordClassifyData.picUrl" style="width:100px; height:100px; line-height:100px; font-size:30px; color:#aaa;">
            <span>+</span>
          </div>
          <div v-else style="width:100px; height:100px;"><img :src="recordClassifyData.picUrl" style="width:100%; height:100%;" alt=""></div>
        </Upload>
      </div>
      
      <template #footer>
        <div style="text-align:center;">
          <Button style="margin-right:5em;" @click="optClassifyImgModal = false">取消操作</Button>
          <Button type="primary" @click="confirmSubClassifyImg">确定提交</Button>
        </div>
      </template>
    </Modal>

  </div>
</template>

<script>
import { Message,Modal } from 'view-ui-plus'
import { defineComponent,reactive,ref,getCurrentInstance, onMounted} from 'vue'
import { useRouter,useRoute} from 'vue-router'
import {compressFileM} from '@/utils/system/uploadCompress.js'
import {cow} from '@/request/api'
import api from '@/request/apiConfig' //真实接口配置
export default defineComponent({
  components:{
    
  },
  setup() {
    let {proxy} = getCurrentInstance();
    const route = useRoute()
    const router = useRouter()

    const token = localStorage.aynUserToken
    const uploadUrl = api.apiManager + '/manager/images/upload'

    let dataSource = ref([])
    const classifyTreePropsSet = {label:'name'}

    let optClassifyModal = ref(false)
    let optClassifyModalTitle = ref('新增分类')
    let optClassifyForm = reactive({name:'',sort:null,reqRandom:''})
    let optClassifyRule = ref({
      name: [{ required: true, message: '请填写分类名称', trigger: 'blur' }],
      sort: [{ required: true, type:'number', message: '请填写分类输出顺序', trigger: 'blur' }],
    })

    // 获取全部分类内容
    async function getAllClassifyData(){
      await cow.getCattleClassify({parentId:0}).then(res=>{
        if(res.code === 101){
          dataSource.value = res.data || []
        }
      })
    }

    // 新增一级分类
    function addNewClassify(){
      optClassifyForm.name = '',optClassifyForm.sort = ''
      optClassifyModal.value = true
      optClassifyModalTitle.value = '新增分类'
    }

    let recordClassifyData = ref({})  //当前操作分类
    // 编辑数节点
    function editTreeClassify(n,d){
      recordClassifyData.value = JSON.parse(JSON.stringify(d))
      optClassifyForm.name = d.name,optClassifyForm.sort = d.sort
      optClassifyModal.value = true
      optClassifyModalTitle.value = '编辑分类'
    }

    // 添加下级分类
    function addNextClassify(n,d){
      optClassifyForm.name = '',optClassifyForm.sort = ''
      recordClassifyData.value = JSON.parse(JSON.stringify(d))
      optClassifyModal.value = true
      optClassifyModalTitle.value = '添加下级分类'
      console.log('数据',recordClassifyData);
    }

    // 提交操作分类
    function submitOptClassify(){
      proxy.$refs['optClassifyFormRef'].validate(async (valid) => {
        if (valid) {
          let sendParams = JSON.parse(JSON.stringify(optClassifyForm))
          let repFun = ''
          // 新增一级分类
          if(optClassifyModalTitle.value === '新增分类'){
            sendParams.parentId = "0"
            repFun = cow.addCowClassify
          }
          // 添加下级分类
          else if(optClassifyModalTitle.value === '添加下级分类'){
            sendParams.parentId = recordClassifyData.value.id
            repFun = cow.addCowClassify
          }
          // 编辑分类
          else if(optClassifyModalTitle.value === '编辑分类'){
            console.log(recordClassifyData.value);
            sendParams = JSON.parse(JSON.stringify(recordClassifyData.value))
            sendParams.name = optClassifyForm.name
            sendParams.sort = optClassifyForm.sort
            repFun = cow.updateCowClassify
          }
          await repFun(sendParams).then(res=>{
            if(res.code === 101){
              optClassifyModal.value = false
              Message.success({ content: res.retMsg || '操作成功'})
              getAllClassifyData()
            }else{
              Message.error({content: res.retMsg || '操作失败'})
            }
          }).catch(e=>{
            Message.error({content: e.retMsg || '操作失败'})
          })
        } else {
          Message.warning({content: '请填写完整内容'})
        }
      })
    }

    // 删除分类
    function delClassidy(n,d){
      Modal.confirm({
        title: '温馨提示',
        content: `<p>您确定要删除 <b>${d.name}</b> 分类吗？</p>`,
        onOk:async () => {
          cow.deleteCowClassify({ids:d.id}).then(res=>{
            if(res.code === 101){
              Message.success(res.retMsg || '操作成功');
              getAllClassifyData()
            }else{
              Message.error({content: res.msg || '操作失败'})
            }
          }).catch(e=>{
            Message.error({content: e.msg || '操作失败'})
          })
        },
        onCancel: () => {
          Message.info('您已取消操作');
        }
      });
    }

    let optClassifyImgModal = ref(false)
    // 操作分类图片
    function optClassifyImg(n,d){
      recordClassifyData.value = JSON.parse(JSON.stringify(d))
      optClassifyImgModal.value = true
    }

    function handleBeforeUpload(file){
      // 进行2.5倍系数压缩
      return (compressFileM(file,2.5))
    }

    function handleSuccess (res, file) {
      if(res.code === 101){
        recordClassifyData.value.picUrl = res.data
      }
      console.log('结果输出',recordClassifyData.value);
    }

    function handleFormatError (file) {
      this.$Notice.warning({
          title: '温馨提示',
          desc: '上传失败！'
      });
    }

    async function confirmSubClassifyImg(){
      let sendParams = JSON.parse(JSON.stringify(recordClassifyData.value))
      await cow.updateCowClassify(sendParams).then(res=>{
        if(res.code === 101){
          Message.success(res.retMsg || '操作成功');
          optClassifyImgModal.value = false
          getAllClassifyData()
        }else{
          Message.error({content: res.msg || '操作失败'})
        }
      }).catch(e=>{
        Message.error({content: e.msg || '操作失败'})
      })
    }
    
    // 初始化挂载
    onMounted(async ()=>{
      getAllClassifyData() //获取分类树
    })

    return {
      dataSource,optClassifyModal,optClassifyModalTitle,optClassifyForm,optClassifyRule,recordClassifyData,
      classifyTreePropsSet,optClassifyImgModal,uploadUrl,token,
      editTreeClassify,addNewClassify,submitOptClassify,addNextClassify,delClassidy,optClassifyImg,handleSuccess,
      handleFormatError,handleBeforeUpload,confirmSubClassifyImg
    }
  },
  methods: {
    
  }
})
</script>

<style lang="scss" scoped>
.classifyManage{
  padding: 2em;
  .tree_content{
    background-color: #fff;
    padding: 2em; margin: 2em 0;
  }  
  .upload_classify_img{
    .upload_border{
      width: 100%; height: 100%;
    }
  }
}
</style>
<style lang="scss">
.classifyManage{
  .el-tree-node__label{
    border: 1px solid #000;
    width: 100%;
  }
  .custom-tree-node {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
    span{
      width: 33%;
    }
  }
  .ivu-upload-drag{
    border: 0px;
  }
}
</style>