/**
  // author：zhangyy
  // time:2023-03-22
  // desc:新增采购需求
*/
<template>
  <div class="addNeeds">
    <div>
     <Form ref="newCowForm" :model="newContentForm" :rules="newContentRule" :label-width="150">
        <Divider orientation="left"><b>采购信息</b></Divider>
        <Form-item label="采购牛只类别" prop="classifyId">
          <Cascader :data="classifyDataList" v-model="newContentForm.classifyId" @on-change="changeSelClassify" style="width:30%;" />
        </Form-item>
        <Form-item label="意向采购单价" prop="buyPrice">
          <InputNumber v-model="newContentForm.buyPrice" placeholder="请输入意向采购单价"  style="width: 30%" />&nbsp;&nbsp;&nbsp;
          <RadioGroup v-model="newContentForm.priceUnitCode">
            <Radio :label="1">元/头</Radio>
            <Radio :label="2">元/公斤</Radio>
            <Radio :label="3">元/斤</Radio>
          </RadioGroup>
        </Form-item>
        <Form-item label="采购数量" prop="buyCount" min-width="130">
          <InputNumber v-model="newContentForm.buyCount " placeholder="请输入采购数量"  style="width: 30%" />&nbsp;&nbsp;&nbsp;
          <RadioGroup v-model="newContentForm.countUnitCode">
            <Radio :label="1">头</Radio>
            <Radio :label="2">公斤</Radio>
            <Radio :label="3">斤</Radio>
          </RadioGroup>
        </Form-item>
        <Form-item label="牛只重量" prop="weight">
          <Select :label-in-value="true" v-model="newContentForm.weight" multiple style="width:30%" placeholder="请选择牛只规格重量（多选）">
            <Option v-for="item in cowWeightList" :value="item" :key="item" >{{ item }}</Option>
          </Select>
        </Form-item>
        <Form-item label="牛只膘情">
          <Input v-model="fat" placeholder="请输入内容" style="width: 20%"></Input>
          <Button type="primary" style="margin-left:20px" @click="addFatInfo">确定生成</Button>
        </Form-item>
        <Form-item label="" prop="fatInfoList">
          <Tag v-for="(item,index) in newContentForm.fatInfoList" :key="item" :name="item" @on-close="delTag(index)" color="#B62D4A" closable>{{ item }}</Tag>
        </Form-item>
        <Form-item label="采购地区" prop="blongArea">
          <Cascader :data="areadata" change-on-select v-model="newContentForm.blongArea"  @on-change="changeSelArea" style="width:30%" />
        </Form-item>
        <Form-item label="采购要求" prop="buyContent">
          <BasicEditor ref="editotTool"></BasicEditor>
        </Form-item>
      </Form>
    </div>
    <div style="text-align:center;margin-bottom:3em;">
      <Button @click="" style="margin-right:3em;">取消返回</Button>
      <Button type="warning" @click="confirmSubAddNewCow(0)" style="margin-right:3em;">保存草稿</Button>
      <Button type="primary" @click="confirmSubAddNewCow(1)">直接发布</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 areadata from '../beefSaleManage/assets/area.json'
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();
    let newContentForm = reactive({
      classifyId:[],buyCount:null,blongArea:[],buyPrice:null,fatInfoList:[],weight:[],priceUnitCode:1,countUnitCode:1,
      buyContent:'',classifyOne:'',classifyOneName:'',classifyTwo:'',classifyTwoName:'',classifyThree:'',classifyThreeName:'',province:'',city:'',area:'',
    })
    // 表单验证项
    let newContentRule = ref({
      classifyId: [{ required: true, type:'array', message: '请选择采购牛只类别', trigger: 'change' }],
      buyCount: [{ required: true, type:'number', message: '请输入采购数量', trigger: 'change' }], 
      blongArea: [{ required: true, type:'array', message: '请选择采购地区', trigger: 'change' }],
      priceUnitCode:[{ required: true, message: '请选择采购单价单位', trigger: 'change' }],
      countUnitCode:[{ required: true, message: '请选择采购数量单位', trigger: 'change' }],
      buyPrice:[
        { required: true, message: '请输入意向采购单价'},
        // { message: '小数保留2位', trigger:'change', pattern:/^(([1-9]\d{0,3})|0)(\.\d{0,2})?$/,}
      ],
      fatInfoList: [{ required: true,type:'array', message: '请填写牛只膘情', trigger: 'change' }],
      weight: [{ required: true,type:'array',  message: '请选择牛只重量', trigger: 'change' }],
    })

    // 获取全部牛只分类内容
    let classifyDataList = ref([])  //分类列表数据
    async function getAllClassifyData(){
      await cow.getCattleClassify().then(res=>{
        if(res.code === 101){
          let finalData = rinseClassiftData(res.data)
          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:''
    }

    let fat = ref('')
    // 生成牛只膘情
    function addFatInfo(){
        if(fat.value == ''){
            Message.error({content: '请输入牛只膘情'})
        }else{
            newContentForm.fatInfoList.push(fat.value)
            newContentForm.fatInfo = newContentForm.fatInfoList.toString()
            fat.value = ''
        }
    }
    
    // 删除一个膘情信息
    function delTag(ind){
      this.newContentForm.fatInfoList.splice(ind,1)
      this.newContentForm.fatInfo = this.newContentForm.fatInfoList.toString()
    }

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

    function handleFormatError (file) {
      Message.error({content: '文件格式不正确'})
    }
    
    // 选择牛只规格
    function changeSelWeight(val){
      console.log('牛只规格',val);
      newContentForm.weight = val
    }

    // 上架或保存仓库
    function confirmSubAddNewCow(type){
      newContentForm.buyContent = proxy.$refs.editotTool.valueHtml  //富文本传值
      proxy.$refs['newCowForm'].validate(async (valid) => {
        if (valid) {
          let sendParams = JSON.parse(JSON.stringify(newContentForm))
          sendParams.status = type
          let tipFont = ''
          type == 0? tipFont = '保存草稿': tipFont ='直接上架'
          Modal.confirm({
              title: '温馨提示',
              content: `<p>您确定将当前采购需求<b> ${tipFont} </b>?</p>`,
              onOk: () => {
                subreq()
              },
              onCancel: () => {
                Message.info('您已取消操作');
              }
          });
          // 提交请求
          async function subreq(){
            Spin.show()
            await cow.saveCattleBuyDemand(sendParams).then(res=>{
              Spin.hide()
              if(res.code == 101){
                Message.success({content: res.message || '操作成功'})
                router.push('procurementNeeds')
              }else{
                Message.error({content: res.message || '操作失败'})
              }
            }).catch(e=>{
              Spin.hide()
              Message.error({content: e.message || '操作失败'})
            })
          }
          
        } else {
          Message.warning({content:'请填写完表单数据'})
        }
      })
    }

    onMounted(async()=>{
      getAllClassifyData()  //获取全部分类
      getCowWeightSelList() //获取牛只选择体重列表
    })

    return {
      fat,newContentRule,newContentForm,
      classifyDataList,areadata,cowWeightList,
      handleFormatError,changeSelWeight,changeSelClassify,
      changeSelArea,confirmSubAddNewCow,addFatInfo,delTag
    }
  },
  methods: {
    
  },
})
</script>

<style lang="scss" scoped>
.addNeeds{
  padding: 1em;
}
</style>
<style lang="scss">
.addNeeds{

}
</style>