/**
  // author：zhangyy
  // time:2023-03-22
  // desc:采购需求列表
*/
<template>
  <div class="procurementNeeds">
     <!-- 筛选 -->
     <Row :gutter="8">
      <Col span="3">
        <Select v-model="filtInfoData.status" clearable placeholder="采购信息状态">
          <Option v-for="item in needStatus" :value="item.value" :key="item.value">{{ item.label }}</Option>
        </Select>
      </Col>
      <Col span="5">
        <Cascader placeholder="请选择牛只分类" :data="classifyDataList" change-on-select v-model="filtInfoData.classifyId" @on-change="changeSelClassify" />
      </Col>
      <Col span="4">
        <DatePicker type="date" placeholder="请选择开始时间" v-model="filtInfoData.startDate" @on-change="changeStartDate"  />
      </Col>
      <Col style="display:inline-block;margin-top:5px"> —</Col>
      <Col span="4">
        <DatePicker type="date" placeholder="请选择结束时间" v-model="filtInfoData.endDate" @on-change="changeEndDate" />
      </Col>
      <Col span="5">
        <Button type="primary" @click="getData">搜索</Button>
      </Col>
      <Col span="2">
        <Button type="success" @click="$router.push('addNeeds')">新增采购需求</Button>
      </Col>
    </Row>
    <!-- 表格部分 -->
    <el-table :data="needTabData.data" border style="width: 100%; margin-top:20px;">
      <el-table-column type="index" label="序号" width="55" align="center" />
      <el-table-column label="添加时间" width="180">
        <template #default="scope">
          {{ moment(scope.row.addTime).format('yyyy-MM-DD hh:mm:ss') || '暂无'}}
        </template>
      </el-table-column>
      <el-table-column label="牛只分类" width="200">
        <template #default="scope">
          {{ scope.row.classifyOneName}}/{{scope.row.classifyTwoName }}/{{scope.row.classifyThreeName  }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="100">
        <template #default="scope">
          <Tag color="green" v-if="scope.row.status == 1">展示中</Tag>
          <Tag color="magenta" v-if="scope.row.status == 0">已下架</Tag>
        </template>
      </el-table-column>
      <el-table-column prop="buyPrice" label="意向采购单价" align="center" width="130">
        <template #default="scope">
          <Numeral :value="scope.row.buyPrice" format="0,0.00" style="color:#D64E47; font-weight:bold;">
            <template #suffix>
              <strong>{{scope.row.priceUnitCode == 1? ' 元/头':(scope.row.priceUnitCode == 2?" 元/公斤":' 元/斤' )}}</strong>
            </template>
          </Numeral>
        </template>
      </el-table-column>
      <el-table-column label="采购数量" prop="buyCount" align="center" min-width="100">
        <template #default="scope">
          {{ scope.row.buyCount }} {{scope.row.countUnitCode == 1? '头':(scope.row.countUnitCode == 2?"公斤":'斤' )}}
        </template>
      </el-table-column>
      <el-table-column label="牛只重量" prop="weight" min-width="120">
        <template #default="scope">
          <Tag color="blue" v-for="(item,index) in scope.row.weightList" :key="index">{{item}}</Tag>
        </template>
      </el-table-column>
      <el-table-column label="牛只膘情" min-width="120">
        <template #default="scope">
          <Tag color="#B62D4A" v-for="(item,index) in scope.row.fat" :key="index">{{item}}</Tag>
        </template>
      </el-table-column>
      <el-table-column label="采购地区" min-width="130">
        <template #default="scope">
          <Icon type="md-pin" color="#2db7f5" /> 
          <span style="color:#999; font-size:12px;">{{ scope.row.province}}-{{ scope.row.city}}-{{scope.row.area}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200"  fixed="right">
        <template  #default="scope">
          <Button  size="small" type="primary" ghost @click="needsDetail(scope.row.id)" style="margin-right:5px">查看详情</Button>
          <Button  size="small" type="success" @click="offSafe(scope.row.id,1)" v-if="scope.row.status == 0">发布信息</Button>
          <Button  size="small" type="warning" @click="offSafe(scope.row.id,0)" v-if="scope.row.status == 1">下架信息</Button>
          <Button  size="small" type="primary" @click="editNeeds(scope.row.id)" v-if="scope.row.status == 0" style="margin-top:5px;margin-right:5px" >编辑信息</Button>
          <Button  size="small" type="error" @click="delNeeds(scope.row.id)" v-if="scope.row.status == 0" style="margin-top:5px;">删除信息</Button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="page_style">
      <Page :total="needTabData.total" :model-value="currentPage" show-elevator show-total @on-change="changePage" />
    </div>
  </div>
</template>

<script>
import { defineComponent, ref ,reactive, onMounted} from 'vue'
import { cow } from '@/request/api'
import { Message,Modal,Spin } from 'view-ui-plus'
import moment from 'moment'

export default defineComponent({
  components:{
    
  },
  setup() {
   
   let filtInfoData = reactive({ // 搜索
      limit:10,offset:0,
    })

    let needStatus = reactive([
        {
            value: 1,
            label: '展示中'
        },
        {
            value: 0,
            label: '已下架'
        },
    ])

    let needTabData = ref([])  // 列表数据

    //获取列表内容
    async function getData(){
      await cow.getBuyDemandPage(filtInfoData).then(res =>{
        if (res.code == 101) {
          res.data.forEach(element => {
            element.fat = []
            element.fat = element.fatInfo.split(",");
            element.weightList = []
            let arr = element.weight.split(",");
            arr.forEach(e=>{
              element.weightList.push(e.replace(/\"/g, "").replace(/\[/g, "").replace(/\]/g, ""))
            }) 
          });
          needTabData.value = res
        }
      })
    }

    // 获取全部牛只分类内容
    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
    }
    
    // 改变选择的分类
    function changeSelClassify(val,arr){
      filtInfoData.classifyOne = arr[0]?arr[0].value:''
      filtInfoData.classifyTwo = arr[1]?arr[1].value:''
      filtInfoData.classifyThree = arr[2]?arr[2].value:''
    }

    let currentPage = ref(1)
    //更改页码
    function changePage (page) {
      if(needTabData.value.limit){
        filtInfoData.offset = (page -1) *  needTabData.value.limit  //更新偏移量
        currentPage = page  //切换当前页码
        getData() 
      }
    }

    // 搜索日期格式
    function changeEndDate(val){
      filtInfoData.endDate = val;
    }

    function changeStartDate(val){
      filtInfoData.startDate = val
    }

    //牛只下架
    function  offSafe(id,type){
      let tipFont = ''
        type == 0? tipFont = '下架': tipFont ='发布'
        Modal.confirm({
          title: '温馨提示',
          content: `<p>您确定将当前采购需求<b> ${tipFont} </b>?</p>`,
          onOk: () => {
            confirmOffSafe()
          },
          onCancel: () => {
            Message.info('您已取消操作');
          }
        });
        const params = {
          id:id,
          status: type
        }
      //确定下架
      async function confirmOffSafe() {
        await cow.offOnSale(params).then(res =>{
          if (res.code == 101) {
            Message.success(type == 0?'下架成功': '发布成功')
            getData()
          }else{
            Message.error(res.message)
          }
        })
      }
    }
    // 查看详情
    function needsDetail(id){
      this.$router.push({path:'procurementDetail',query:{id:id}})
    }

    // 编辑
    function editNeeds(id){
      this.$router.push({path:'editNeeds',query:{id:id}})
    }

    // 删除
    function delNeeds(id){
      Modal.confirm({
          title: '温馨提示',
          content: `<p>您确定将当前采购需求<b>删除</b>?</p>`,
          onOk: () => {
            confirmDel()
          },
          onCancel: () => {
            Message.info('您已取消操作');
          }
        });
        const params = {
          id:id,
          deleted:'1' 
        }
      //确定
      async function confirmDel() {
        await cow.updateCattleBuyDemand(params).then(res =>{
          if (res.code == 101) {
            Message.success('删除成功')
            getData()
          }else{
            Message.error(res.message)
          }
        })
      }
    }

    onMounted(()=>{
      getData() 
      getAllClassifyData()  //获取全部分类

    })

    return {
      needStatus,needTabData,filtInfoData,currentPage,classifyDataList,getAllClassifyData,moment,
      getData,changePage,changeSelClassify,offSafe,needsDetail,editNeeds,delNeeds,changeStartDate,changeEndDate
    }
  },
})
</script>

<style lang="scss" scoped>
.procurementNeeds{
  padding: 1em;
  .page_style{
    text-align: right; margin-top: 1em;
    background-color: var(--system-container-background);
  }
}
</style>