/**
  // author：zhangb
  // time:2023-01-09
  // desc:编辑牛只
*/
<template>
  <div class="editBeef">
    <div>
     <Form ref="newCowForm" :model="newContentForm" :rules="newContentRule" :label-width="120">

        <Divider orientation="left"><b>基本信息</b></Divider>
        <Form-item label="商品名称" prop="name">
          <Input v-model="newContentForm.name" placeholder="请输入内容名称" style="width: 480px"></Input>
        </Form-item>
        <Form-item label="所属分类" prop="classifyId">
          <Cascader :data="classifyDataList" v-model="newContentForm.classifyId" @on-change="changeSelClassify" style="width:30%;" />
        </Form-item>
        <Form-item label="牛只所在地" prop="blongArea">
          <Cascader :data="areadata" change-on-select v-model="newContentForm.blongArea" class="areaClass" :placeholder="pleasett" @on-change="changeSelArea" style="width:30%" :clearable="false"/>
        </Form-item>
        <Form-item label="详细地址" prop="addressInfo">
          <Input v-model="newContentForm.addressInfo" type="textarea" placeholder="请输入链接地址" style="width: 480px"></Input>
        </Form-item>

        <Divider orientation="left" style="margin-top:2em;"><b>牛只规格</b></Divider>
        <Form-item label="牛只重量">
          <Select :key="updateKey" :label-in-value="true" v-model="selectCowWeight" multiple style="width:45%" @on-change="changeSelWeight" placeholder="请选择牛只规格重量（多选）">
            <Option v-for="item in cowWeightList" :value="item" :key="item" >{{ item }}</Option>
          </Select>
          <Button type="success" style="margin-left:3em" @click="confirmCreateVersion">确定生成规格明细</Button>
        </Form-item>
        
        <!-- 表格生成规格 -->
        <div style="width: 90%; margin:0 auto; margin-bottom:2em;">
          <div style="font-size:13px; margin:1em 0;"> <Tag color="red">当前规格</Tag></div>
          <el-table :data="cattleSkuList" >
            <el-table-column type="index" label="序号" width="65" align="center" />
            <el-table-column prop="weight" label="规格重量"  width="140" />
            <el-table-column label="牛只数量" max-width="200">
              <template #default="scope">
                <Input v-model="scope.row.count" placeholder="牛只数量" style="width: 90%"></Input>
              </template>
            </el-table-column>
            <el-table-column label="牛只价格" max-width="200">
              <template #default="scope">
                <Input v-model="scope.row.price" placeholder="牛只价格" style="width: 90%"></Input>
              </template>
            </el-table-column>
            <el-table-column label="单位" max-width="200">
              <template #default="scope">
                <Input v-model="scope.row.unit" placeholder="单位" style="width: 90%"></Input>
              </template>
            </el-table-column>
            <el-table-column label="起售量" max-width="200">
              <template #default="scope">
                <Input v-model="scope.row.quantity" placeholder="起售量" style="width: 90%"></Input>
              </template>
            </el-table-column>
            <el-table-column prop="address" label="规格图片" >
              <template #default="scope">
                <Upload
                  ref=""
                  type="drag"
                  :action="uploadUrl"
                  :headers="{'X-AIYANGNIU-SIGNATURE':token}"
                  :show-upload-list="false"
                  :on-success="verHandleSuccess"
                  :before-upload="(e)=>verBeforeUpload(e,scope.$index)"
                  :format="['jpg','jpeg','png']"
                  :max-size="2048"
                  :on-format-error="handleFormatError"
                  class="upload_version_img">
                  <div v-if="!scope.row.imgUrl" class="upload_border">
                    <span>+</span>
                  </div>
                  <div v-else style="width:100px;height:100px;"> <img :src="scope.row.imgUrl" style="width:100%; height:100%;" alt=""></div>
                </Upload>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <Form-item label="看牛模式" prop="previewType">
          <Select v-model="newContentForm.previewType" :label-in-value="true" placeholder="请选择看牛模式" style="width:30%">
            <Option v-for="type in lookCowType" :key="type.typeVal" :value="type.typeVal">{{type.typeLabel}}</Option>
          </Select>
        </Form-item>

        <Form-item label="看牛定金" prop="previewMoney">
          <InputNumber v-model="newContentForm.previewMoney" placeholder="请输入看牛定金"  style="width: 15%" />&nbsp;&nbsp;&nbsp;元 / 头
        </Form-item>

        <Form-item label="牛只展示图" prop="mainImgData">
          <div class="demo-upload-list" v-for="item in mainUploadCowImg" :key="item">
            <template v-if="item.status === 'finished'">
              <Image :src="item.url" fit="cover" width="100%" height="100%" />
              <div class="demo-upload-list-cover">
                <Icon type="ios-eye-outline" @click="handleView(item.url)"></Icon>
                <Icon type="ios-trash-outline" @click="handleRemove(item)"></Icon>
              </div>
            </template>
            <template v-else>
              <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
            </template>
          </div>
          <Upload
            ref="mainImgUpload"
            :headers="{'X-AIYANGNIU-SIGNATURE':token}"
            :show-upload-list="false"
            :on-success="handleSuccess"
            :format="['jpg','jpeg','png']"
            :on-format-error="handleFormatError"
            :before-upload="beforeUpload"
            multiple
            type="drag"
            :action="uploadUrl"
            style="display: inline-block;width:58px;">
            <div style="width: 58px;height:58px;line-height: 58px;">
              <Icon type="ios-camera" size="20"></Icon>
            </div>
          </Upload>
          <ImagePreview v-model="preViewImgModel" :preview-list="preViewImg" />
          <div style="color:#aaa;font-size:12px;">图片格式为 jpg、jpeg、png</div>
        </Form-item>
       
        <Form-item label="牛只详情" prop="content">
          <BasicEditor ref="editotTool"></BasicEditor>
        </Form-item>
      </Form>
    </div>
    <div style="text-align:center;margin-bottom:3em;">
      <Button @click="$router.back()" style="margin-right:3em;">取消返回</Button>
      <Button type="warning" @click="confirmSubAddNewCow(1)" style="margin-right:3em;">保存在仓库中</Button>
      <Button type="primary" @click="confirmSubAddNewCow(3)">直接上架牛源</Button>
    </div>
  </div>
</template>

<script>
import { Message,Modal,Spin } from 'view-ui-plus'
import { defineComponent, reactive,getCurrentInstance,onMounted,ref} from 'vue'
import BasicEditor from '@/components/wangEditor/BasicEditor.vue'
import {compressFileM} from '@/utils/system/uploadCompress.js'
import areadata from './assets/area.json'
import api from '@/request/apiConfig' //真实接口配置
import router from '@/router'
import {cow} from '@/request/api'
import { useRouter } from 'vue-router';

export default defineComponent({
  components:{
    BasicEditor
  },
  setup() {
    const $router = useRouter();
    let {proxy} = getCurrentInstance();
    const token = localStorage.aynUserToken
    let newContentForm = reactive({
      classifyId:[] ,blongArea: [], addressInfo:'',previewType:'',previewMoney:null,name:'',mainImgData: [],content:'',classifyOne:'',
      classifyOneName:'',classifyTwo:'',classifyTwoName:'',classifyThree:'',classifyThreeName:'',province:'',city:'',area:'',picUrl:'',
    })
    // 表单验证项
    let newContentRule = ref({
      classifyId: [{ required: true, type:'array', message: '请选择所属类别', trigger: 'change' }],
      blongArea: [{ required: true, type:'array', message: '请选择牛只所在地', trigger: 'change' }],
      addressInfo:[{ required: true, message: '请填写详细地址', trigger: 'blur' }],
      previewType:[{ required: true, type:'number', message: '请选择看牛模式', trigger: 'change' }],
      previewMoney:[
        { required: true, message: '请输入看牛订金',},
        { message: '小数保留2位', trigger:'change', pattern:/^(([1-9]\d{0,3})|0)(\.\d{0,2})?$/,}
      ],
      name: [{ required: true, message: '请填写内容名称', trigger: 'blur' }],
      isShow: [{ required: true, message: '请选择展示状态', trigger: 'change' }],
      mainImgData:[{ required: true, type:'array', message: '请上传牛只主图', trigger: 'change' }],
    })
    const uploadUrl = api.apiManager + '/manager/images/upload'
    let lookCowType = ref([
      {typeVal:1,typeLabel:'预约看牛：先预约，后到现场看牛'},
      {typeVal:2,typeLabel:'现场看牛：现场看牛，无需预约'},
    ])
    

    // 获取全部牛只分类内容
    let classifyDataList = ref([])  //分类列表数据
    async function getAllClassifyData(){
      await cow.getCattleClassify().then(res=>{
        if(res.code === 101){
          let finalData = rinseClassiftData(res.data)
          console.log('结果数据',finalData);
          classifyDataList.value = finalData
        }
      })
    }

    // 清洗分类数据
    function rinseClassiftData(data){
      data = JSON.parse(JSON.stringify(data).replace(/name/g, 'label'))
      data = JSON.parse(JSON.stringify(data).replace(/id/g, 'value'))
      return data
    }
    
    let cowWeightList = ref([])
    // 获取牛只体重列表
    function getCowWeightSelList(){
      cow.getCattleWeightScopes().then(res=>{
        if(res.code === 101){
          cowWeightList.value = res.data || []
        }
      })
    }

    // 改变选择的分类
    function changeSelClassify(val,arr){
      newContentForm.classifyOne = arr[0]?arr[0].value:''
      newContentForm.classifyOneName = arr[0]?arr[0].label:''
      newContentForm.classifyTwo = arr[1]?arr[1].value:''
      newContentForm.classifyTwoName = arr[1]?arr[1].label:''
      newContentForm.classifyThree = arr[2]?arr[2].value:''
      newContentForm.classifyThreeName = arr[2]?arr[2].label:''
    }

    function changeSelArea(val,arr){
      newContentForm.province = arr[0]?arr[0].label:''
      newContentForm.provinceCode = arr[0]?arr[0].value:''
      newContentForm.city = arr[1]?arr[1].label:''
      newContentForm.area = arr[2]?arr[2].label:''
    }

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

    let mainUploadCowImg = ref([])  //主图列表
    function handleSuccess(res, file, fileList){
      if(res.code === 101){
        file.url = res.data
        newContentForm.mainImgData = mainUploadCowImg.value
      }
    }

    let optVersionIndex = ref('')  //记录操作规格下标

    let selectCowWeight = ref([]) //多选牛只数据
    let cattleSkuList = ref([]) //牛只规格数据

    // 规格单独上传内容
    function verBeforeUpload(file,ind){
      console.log('返回内容',file,ind);
      optVersionIndex = ind
    }
    
    function verHandleSuccess(res, file, fileList){
      if(res.code == '101'){
        cattleSkuList.value[optVersionIndex].imgUrl = res.data
      }
    }

    function handleFormatError (file) {
      Message.error({content: '文件格式不正确'})
    }
    
    // 选择牛只规格
    function changeSelWeight(val){
      console.log('牛只规格',val);
      selectCowWeight = val
    }
    // 生成规格明细
    function confirmCreateVersion(){
      cattleSkuList.value = []
      selectCowWeight.forEach(item => {
        let newobj = {}
        newobj.weight = item.label
        newobj.selWifghtVal = item.value
        newobj.count = null
        newobj.price = null
        newobj.unit = null
        newobj.quantity = null
        newobj.imgUrl = ''
        cattleSkuList.value.push(newobj)
      })
    }

    // 预览上传主图
    let preViewImg = ref([])
    let preViewImgModel = ref(false)
    function handleView (name) {
      preViewImg.value = [name];
      preViewImgModel.value = true;
    }

    function handleRemove (file) {
      const fileList = proxy.$refs.mainImgUpload.fileList;
      proxy.$refs.mainImgUpload.fileList.splice(fileList.indexOf(file), 1);
    }

    const updateKey = ref(0);
    const pleasett = ref('请选择')
    // 查询商品详情
    async function getInitData(){
      const params ={
        spuId:$router.currentRoute.value.query.id
      }
      await cow.getCattleSpu(params).then(res =>{
        if (res.code == 101) {
          Object.assign(newContentForm,res.data);
          newContentForm.classifyId = [res.data.classifyOne,res.data.classifyTwo,res.data.classifyThree]
          pleasett.value = res.data.province +' / '+res.data.city+' / '+res.data.area
          res.data.cattleSkuList.forEach((e,index) =>{   // 规格下拉回显
            selectCowWeight.value.push(e.weight)
          })
          updateKey.value += 1;
          cattleSkuList.value = res.data.cattleSkuList  // 规格列表回显
          let imgArr = []    // 预览图回显
          imgArr = res.data.picUrl.split("#");
          imgArr.forEach(e=>{
            mainUploadCowImg.value.push({url:e,status:'finished'})
          })
          newContentForm.blongArea = ['北京']
          newContentForm.mainImgData = mainUploadCowImg.value
          proxy.$refs.editotTool.valueHtml =res.data.content  // 富文本回显
        }else{
          Message.error(res.message)
        }
      })
    }

    // 上架或保存仓库
    function confirmSubAddNewCow(type){
      newContentForm.content = proxy.$refs.editotTool.valueHtml  //富文本传值
      proxy.$refs['newCowForm'].validate(async (valid) => {
        if (valid) {
          let sendParams = JSON.parse(JSON.stringify(newContentForm))
          sendParams.picUrl = proxy.$refs.mainImgUpload.fileList.map(list=>{return list.url}).join('#')
          sendParams.cattleSkuList = cattleSkuList.value
          sendParams.skuStatus = type
          console.log('最终组合的参数',sendParams);
          let tipFont = ''
          type == 1? tipFont = '保存至仓库中': tipFont ='直接上架销售'
          Modal.confirm({
              title: '温馨提示',
              content: `<p>您确定将当前牛只信息<b> ${tipFont} </b>?</p>`,
              onOk: () => {
                subreq()
              },
              onCancel: () => {
                Message.info('您已取消操作');
              }
          });
          // 提交请求-编辑
          async function subreq(){
            Spin.show()
            await cow.updateCattleSpu(sendParams).then(res=>{
              Spin.hide()
              if(res.code == 101){
                Message.success({content: res.message || '操作成功'})
                console.log(type,"type")
                type == 1?router.push('beefInStore'):router.push('beefOnsaleList')
              }else{
                Message.error({content: res.message || '操作失败'})
              }
            }).catch(e=>{
              Spin.hide()
              Message.error({content: e.message || '操作失败'})
            })
          }
          
        } else {
          Message.warning({content:'请填写完表单数据'})
        }
      })
    }

    onMounted(async()=>{
      mainUploadCowImg.value = proxy.$refs.mainImgUpload.fileList
      getAllClassifyData()  //获取全部分类
      await getCowWeightSelList() //获取牛只选择体重列表
      getInitData()
    })

    return {
      updateKey,pleasett,uploadUrl,newContentRule,newContentForm,token,classifyDataList,areadata,selectCowWeight,cowWeightList,cattleSkuList,lookCowType,preViewImg,preViewImgModel,mainUploadCowImg,
      beforeUpload,handleFormatError,handleSuccess,confirmCreateVersion,changeSelWeight,verBeforeUpload,verHandleSuccess,handleView,handleRemove,changeSelClassify,
      changeSelArea,confirmSubAddNewCow,getInitData
    }
  },
  methods: {
    
  },
})
</script>

<style lang="scss" scoped>
.editBeef{
  padding: 1em;
  .upload_outer_img{
    max-width: 45%;
    img{
      width: 100%; padding: 0;
    }
    .upload_border{
      width: 100%; padding: 3em;
    }
  }
  .upload_version_img{
    width: 100px; height: 100px;
    border-radius: 2px; overflow: hidden;
    .upload_border{
      line-height: 100px; font-size: 35px; font-weight: bold; color:#ccc;
      background-color: #f9f9f9;
    }
  }
  .demo-upload-list{
    display: inline-block;
    width: 60px;
    height: 60px;
    text-align: center;
    line-height: 60px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    background: #fff;
    position: relative;
    box-shadow: 0 1px 1px rgba(0,0,0,.2);
    margin-right: 4px;
  }
  .demo-upload-list img{
    width: 100%;
    height: 100%;
  }
  .demo-upload-list-cover{
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0,0,0,.6);
  }
  .demo-upload-list:hover .demo-upload-list-cover{
    display: block;
  }
  .demo-upload-list-cover i{
    color: #fff;
    font-size: 20px;
    cursor: pointer;
    margin: 0 2px;
  }
}
</style>
<style lang="scss">
.editBeef{
  .ivu-upload-drag{
    border: 0px;
  }
  .areaClass .ivu-input-default::placeholder{
  color:rgba(0, 0, 0, 0.685) !important;
}
}
</style>