<template>
    <div>
    <Toptitle :title="type==1?'新增费用单据':type==2?'编辑费用单据':'费用单据详情'">
        <Button @click="back" style="margin-right:20px" type="primary">返回</Button>
        <Button type="primary" @click="postData" v-if='type!=3'>保存</Button>
    </Toptitle>
        <Form :label-width='100' class="top_order">
            <FormItem label="费用单据号：" style="width:400px">
                <span v-if="type==3">{{formData.cost_no}}</span>
                <Input disabled placeholder="自动生成费用单据" v-model="formData.cost_no" style='width:200px' v-else/>
            </FormItem>
         <FormItem label="相关项目：" style="width:500px"> 
              <span v-if="type==3">{{formData.order_no}}</span>
              <div style="display:flex;width:100%;" v-else >
             <Select v-model="formData.order_no" filterable clearable style="width:200px" >
               <Option v-for="(item,index) in projectTitleList" :key="index" :value="item.project_number" :label="item.project_name"></Option>
               </Select>
               <Button style="margin-left:20px" type="primary" @click="showProjectModal=true">选择项目</Button>
               </div>
               </FormItem>
            <FormItem label='供应商：' style="width:400px">
                 <span v-if="type==3">{{formData.supply_title}}</span>
         <div v-else style='display:flex;width:300px'>
         <Select filterable clearable v-model="formData.supply_id" >
             <Option v-for="(item,index) in suppliersList" :key="index" :value="item.id" :label="item.title"></Option>
             </Select><Button type="primary"  style="margin-left:20px" @click="showSupplierModal=true">选择供应商</Button>
         </div>
            </FormItem>
         <FormItem label="制单日期：" style="width:400px">
             <span v-if="type==3">{{formData.order_time}}</span>
            <DatePicker type="date" placeholder="年/月/日" style="width: 200px" v-model="formData.order_time" v-else></DatePicker>
         </FormItem>
         <FormItem label='备注：' style="width:300px">
             <span v-if="type==3">{{formData.remark}}</span>
             <Input clearable v-model="formData.remark" v-else/>
         </FormItem>
    </Form>
    <div class="before_table">
      <Button type="primary" @click="addPrice" v-if='type!=3'>增行</Button>
    </div>
    <Table :data='tableData' :columns='type==3?detailTableColumns:tableColumns' border :max-height="type==3?'300':'500'" show-summary :summary-method="handleSummary">
        <template slot="set" slot-scope="{index}">
            <a @click='del(index)'>删除</a>
        </template>
        <template slot="name" slot-scope="{index}">
            <Input v-model="tableData[index].name" placeholder="请输入费用内容" @on-focus='handleFocusName(index)'/>
        </template>
        <template slot="price" slot-scope="{index}">
             <Input v-model="tableData[index].price" @on-change='changePrice($event,index)' @on-focus="priceFocus(index)" @on-blur='priceBlur(index)' type="number"/>
        </template>
        <template slot="total_price" slot-scope="{index}">
             <Input v-model="tableData[index].total_price" @on-change='changeTotalPrice($event,index)' @on-focus="totalPriceFocus(index)" @on-blur='totalPriceBlur(index)' type="number"/>
        </template>
        <template slot="num" slot-scope="{index}">
             <Input v-model="tableData[index].num" @on-change='changeNum($event,index)' @on-blur='priceBlurNum(index)' @on-focus='handleFocusNum(index)' type="number"/>
        </template>
        <template slot="remark" slot-scope="{index}">
             <Input v-model="tableData[index].remark" placeholder="请输入费用备注"/>
        </template>
    </Table>
    <Form v-if="type==3" class="top_order">
      <FormItem label='制单人：' style="width:30%">
          <span>{{formData.user_name}}</span>
      </FormItem>
      <FormItem label='创建时间：' style="width:30%">
           <span>{{formData.crt_time}}</span>
      </FormItem>
      <FormItem label='修改时间：' style="width:30%">
             <span>{{formData.upd_time}}</span>
      </FormItem>
      <FormItem label='审批人：' style="width:30%">
             <span>{{formData.check_name}}</span>
      </FormItem>
      <FormItem label='审批时间：' style="width:30%">
            <span>{{formData.check_time}}</span>
      </FormItem>
    </Form>
     <Modal v-model="showProjectModal"
           title="选择项目"
           width='80'
           @on-ok="handleProjectSelect"
           @on-cancel="showProjectModal=false">
      <div class="modal_content">
        <div class="modal_content_center">
           
          <Form class="modal_content_center_top" :label-width='120'>
               <FormItem label='项目编号：'>
                 <Input type="text"
                   v-model="modalProjectData.project_number"
                   style="width:180px"
                   placeholder="请输入项目编码"
                   clearable
                    />
            </FormItem>
              <FormItem label='项目名称：'>      
            <Input type="text"
                   v-model="modalProjectData.project_name"
                   style="width:180px"
                   placeholder="请输入项目名称" 
                   clearable
                   />
              </FormItem>
           <FormItem label='项目简称：'>
                  <Input type="text"
                   v-model="modalProjectData.abbreviation"
                   style="width:180px"
                   placeholder="请输入项目简称" 
                   clearable
                   />
           </FormItem>
           <FormItem :label-width='40'>
                <Button @click="initProjectModal()"
                    type="primary"
                    style="margin:0 10px;">搜索</Button>
           </FormItem>
           
          </Form>
          <div class="modal_content_center_body">
            <Table :columns="modalProjectTableColumns"
                   height="520"
                   border
                   :loading="modalProjectTableLoading"
                   :data="modalProjectData.tableData">
            </Table>
            <div class="modal_content_center_footer">
              <Page :page-size-opts="[10, 20, 30, 40,100]"
                    @on-page-size-change='changeProjectModalSize'
                    @on-change='changeProjectModalPage'
                    :current='modal_project_page_index'
                    show-total
                    :total="modal_project_total"
                    show-sizer
                    :page-size='modal_project_page_size' />
            </div>
          </div>
        </div>
      </div>
    </Modal>
      <Modal v-model="showSupplierModal"
           title="选择供应商"
           width='80'
           @on-ok="handleSupplierSelect"
           @on-cancel="showSupplierModal=false">
      <div class="modal_content" style="display:flex;">
        <div class="modal_content_left">
          <Tree :data="modalSupplierData.treeData"
                children-key='sub'
                style="width:100%;"
                @on-select-change="handleSupplierTreeSlect"
                class="demo-tree-render"></Tree>
        </div>
        <div class="modal_content_center" style="width:85%">
          <Form class="modal_content_center_top" :label-width='120'>
           <FormItem label='供应商名称：'>
            <Input type="text"
                   clearable
                   v-model="modalSupplierData.title"
                   style="width:180px"
                   placeholder="请输入供应商名称" />
            <Button @click="initSupplierModal(modalSupplierData)"
                    type="primary"
                    style="margin:0 10px;">搜索</Button>
                 </FormItem>   
          </Form>
          <div class="modal_content_center_body">
            <Table :columns="modalSupplierTableColumns"
                   height="520"
                   border
                   :loading="modalSupplierTableLoading"
                   :data="modalSupplierData.tableData"
                   >
            </Table>
            <div class="modal_content_center_footer">
              <Page :page-size-opts="[10, 20, 30, 40,100]"
                    @on-page-size-change='changeSupplierModalSize'
                    @on-change='changeSupplierModalPage'
                    :current='modal_supplier_page_index'
                    show-total
                    :total="modal_supplier_total"
                    show-sizer
                    :page-size='modal_supplier_page_size' />
            </div>
          </div>
        </div>
      </div>
    </Modal>
    </div>
</template>
<script>
export default {
    data(){
        return{
              modalSupplierData: {
        title: '',
        code: '',
        treeData: [
          {
            title: '供应商分类',
            expand: true,
            sub: [],
            render: (h, { root, node, data }) => {
              return h('span', {
                style: {
                  display: 'inline-block',
                  width: '100%'
                }
              }, [
                h('span', [
                  h('Icon', {
                    props: {
                      type: 'ios-folder-outline'
                    },
                    style: {
                      marginRight: '8px'
                    }
                  }),
                  h('span', data.title)
                ]),
                h('span', {
                  style: {
                    display: 'inline-block',
                    // float: 'right',
                    marginRight: '32px'
                  }
                })
              ]);
            },
          }
        ],
        tableData: [{}]
      },
       modalSupplierTableColumns: [
        {
          title: '选择', key: '', align: 'center', minWidth: 60,
          render: (h, params) => {
            let id = params.row.id;
            let flag = false;
            if (this.currentChoose.id == id) {
              flag = true
            } else {
              flag = false
            }
            let self = this
            return h('div', [
              h('Radio', {
                props: {
                  value: flag
                },
                on: {
                  'on-change': () => {
                    self.currentChoose = params.row;
                  }
                }
              })
            ])
          }
        },
        { title: '供应商编码', key: 'code', align: 'center', minWidth: 100 },
        { title: '供应商名称', key: 'title', align: 'center', minWidth: 80, },
        { title: '负责人', key: 'contact', align: 'center', minWidth: 110, },
        { title: '联系方式', key: 'mobile', align: 'center', minWidth: 110, },
      ],
            currentChoose:{},
            showSupplierModal:false,
             modalSupplierTableLoading: false,
      modal_supplier_page_index: 1,
      modal_supplier_page_size: 10,
      modal_supplier_total: 0,
            suppliersList:[],
            modal_project_total:0,
            modalProjectTableLoading:false,
            currentChoose: {},
             modalProjectTableColumns: [
        {
          title: '选择', key: '', align: 'center', minWidth: 60,
          render: (h, params) => {
            let id = params.row.id;
            let flag = false;
            if (this.currentChoose.id == id) {
              flag = true
            } else {
              flag = false
            }
            let self = this
            return h('div', [
              h('Radio', {
                props: {
                  value: flag
                },
                on: {
                  'on-change': () => {
                    self.currentChoose = params.row;
                  }
                }
              })
            ])
          }
        },
      { title: '项目编号', key: 'project_number', align: 'center', minWidth: 100 },
        { title: '项目名称', key: 'project_name', align: 'center', minWidth: 100 },
        { title: '项目简称', align: 'center', key: 'abbreviation', minWidth: 80},
        {
          title: '制单时间', key: 'crt_time', align: 'center', minWidth: 110,
          render: (h, params) => {
            const { row } = params
            return h('span', {}, this.func.replaceDate(row.crt_time))
          }
        },
      ],
            modal_project_page_index:1,
            modal_project_page_size:10,
             modalProjectData: {
        project_number:'',
        abbreviation:'',
        project_name: '',
        tableData: [{}]
      },
            showProjectModal:false,
            type:null,
            formData:{
                  cost_no:'',
                  order_no:'',
                  order_time:new Date(),
                  remark:'',
                  supply_id:'',
            },
            timeData:{
                start_time:'',
                end_time:''
            },
 projectTitleList:[],
 tableData:[],
 tableColumns:[
     {title:'费用明细',align:'center',minWidth:100,key:'name',slot:'name'},
     {title:'数量',align:'center',minWidth:100,key:'num',slot:'num'},
     {title:'单价',align:'center',minWidth:100,key:'price',slot:'price'},
     {title:'金额',align:'center',minWidth:100,key:'total_price',slot:'total_price'},
     {title:'备注',align:'center',minWidth:100,key:'remark',slot:'remark'},
     {title:'操作',align:'center',minWidth:100,key:'set',slot:'set'},
 ],
 detailTableColumns:[
     {title:'费用明细',align:'center',minWidth:100,key:'name'},
     {title:'数量',align:'center',minWidth:100,key:'num'},
     {title:'单价',align:'center',minWidth:100,key:'price'},
     {title:'金额',align:'center',minWidth:100,key:'total_price'},
     {title:'备注',align:'center',minWidth:100,key:'remark'},
 ]
        }
    },
   created(){
       this.type=this.$route.query.type;
        //获取项目名称
        this.axios.get('/api/cut_order_list',{params:{order_type:1}}).then(res=>{
            this.projectTitleList = res.data.data
        })
           // 获取供应商列表
    this.axios({ method: 'get', url: '/api/supply_list', }).then((res) => { this.suppliersList = res.data.data }).catch((err) => { });
        this.initProjectModal();
         // 获取供应商分类
    this.axios({ method: 'get', url: '/api/basic_supply_list', }).then((res) => { this.modalSupplierData.treeData[0].sub = res.data }).catch((err) => { });
        this.initSupplierModal(this.modalSupplierData);
        this.axios.get('/api/warning_list').then(res => { this.warningList = res.data.data })
    },
    mounted(){
        if(this.type!=1){
            this.initData();
        }
    },
    methods:{
         changeSupplierModalSize (e) {
      this.modal_supplier_page_size = e
      this.initSupplierModal(this.modalSupplierData)
    },
    changeSupplierModalPage (e) {
      this.modal_supplier_page_index = e
      this.initSupplierModal(this.modalSupplierData)
    },
           initSupplierModal (searchData) {
      this.axios({
        method: 'get',
        url: '/api/supply_list',
        params: {
          page_index: this.modal_supplier_page_index,
          page_size: this.modal_supplier_page_size,
          title: searchData.title,
          code: searchData.code,
        }
      }).then((res) => {
        this.modal_supplier_total = res.data.total
        this.modalSupplierData.tableData = res.data.data
      }).catch((err) => { });
    },
        handleSupplierTreeSlect (arr, row) {
      this.modalSupplierData.code = row.code
      this.modal_supplier_page_index = 1;
      this.initSupplierModal(this.modalSupplierData)
    },
         handleSupplierSelect () {
      this.formData.supply_id = this.currentChoose.id
    },
        changeProjectModalSize (e) {
      this.modal_project_page_size = e
      this.initProjectModal()
    },
    changeProjectModalPage (e) {
      this.modal_project_page_index = e
      this.initProjectModal()
    },
         initProjectModal () {
      this.axios({
        method: 'get',
        url: '/api/cut_order_list',
         params:{
          page_index: this.modal_project_page_index,
          page_size: this.modal_project_page_size,
          order_type:1,
          project_number:this.modalProjectData.project_number,
          project_name:this.modalProjectData.project_name,
          abbreviation:this.modalProjectData.abbreviation
         }
      }).then((res) => {
        this.modal_project_total = res.data.total
        this.modalProjectData.tableData = res.data.data
      }).catch((err) => { });
    },
         handleProjectSelect () {
      this.formData.order_no = this.currentChoose.project_number;
    },
        initData(){
           this.axios.post('/api/cost_detail',{cost_no:this.$route.query.cost_no}).then(res=>{
               this.formData = JSON.parse(JSON.stringify(res.data));
              delete this.formData.list;
               this.formData.order_time = this.func.replaceDateNoHMS(res.data.order_time);
               this.formData.crt_time = this.func.replaceDate(res.data.crt_time);
               this.formData.upd_time = this.func.replaceDate(res.data.upd_time);
               this.formData.check_time = this.func.replaceDate(res.data.check_time);
               this.tableData = res.data.list;
           })
        },
       handleSummary ({ columns, data }) {
                const sums = {};
                columns.forEach((column, index) => {
                    console.log(data)
                    const key = column.key;
                    if (index === 0) {
                        sums[key] = {
                            key,
                            value: '总价'
                        };
                        return;
                    }
                    const values = data.map(item => Number(item[key]));
                    if (key == 'total_price') {
                        const v = values.reduce((prev, curr) => {
                            const value = Number(curr);
                            if (!isNaN(value)) {
                                return prev + curr;
                            } else {
                                return prev;
                            }
                        }, 0);
                        sums[key] = {
                            key,
                            value:v.toFixed(2)
                        };
                    } else {
                        sums[key] = {
                            key,
                            value: ''
                        };
                    }
                });

                return sums;
        },
        changePrice(e,index){
             this.tableData[index].price = e.target.value;
             this.tableData[index].total_price = (this.tableData[index].num*this.tableData[index].price*1).toFixed(2);
        },
    changeTotalPrice(e,index){
 this.tableData[index].total_price = e.target.value;
             this.tableData[index].price = this.tableData[index].num!=0?(this.tableData[index].total_price/(this.tableData[index].num*1)).toFixed(3):'0.000';
    },
    changeNum(e,index){
 this.tableData[index].num = e.target.value;
             this.tableData[index].total_price = (this.tableData[index].num*this.tableData[index].price*1).toFixed(2);
    },
        handleFocusNum(index){
 this.tableData[index].num='';
        },
        handleFocusName(index){
           this.tableData[index].name='';
        },
        priceBlur(index){
            if(Number(this.tableData[index].price)<0){
               this.tableData[index].price='0.000';
               this.tableData[index].total_price='0.00';
            }else if(this.tableData[index].price===''){
              this.tableData[index].price='0.000';
             this.tableData[index].total_price='0.00';
            }else{
                this.tableData[index].price=Number(this.tableData[index].price).toFixed(3);
                this.tableData[index].total_price=Number(this.tableData[index].total_price).toFixed(2);
                 return
            }
           
        },
        // totalPriceBlur(index),
        priceFocus(index){
            this.tableData[index].price = ''
        },
        totalPriceFocus(index){
          this.tableData[index].total_price = ''
        },
        priceBlurNum(index){
  if(this.tableData[index].num<0||this.tableData[index].num===''){
               this.tableData[index].num = 0;
               this.tableData[index].total_price='0.00';
            }else{
                this.tableData[index].total_price=Number(this.tableData[index].total_price).toFixed(2);
                return
            }
        },
        back(){
           this.$Modal.confirm({
                    title: '是否确认取消',
    
                    onOk: () => {
                        this.$router.go(-1);
                    },
                    onCancel: () => {
                    }
                });
            
        },
        postData(){
            let obj =JSON.parse(JSON.stringify(this.formData));
            let arr = this.tableData.filter(v=>{
                return v.name!='';
            })
            obj.order_time = obj.order_time?Date.parse(obj.order_time).toString().slice(0,10):'';
            if(this.type==1){
                this.axios.post('/api/cost_add',{...obj,children:arr}).then(res=>{
                   if(res.code==200){
                       this.$Message.success(res.msg);
                       this.back();
                   }
               })
            }else{
                 this.axios.post('/api/cost_edit',{...obj,children:arr}).then(res=>{
                   if(res.code==200){
                       this.$Message.success(res.msg);
                       this.back();
                   }
               })
            }
               
        },
        // changeInput(e,index){
        //       this.tableData[index].name = e.target.value;
        // },
        del(index){
           this.tableData.splice(index,1)
        },
        addPrice(){
            let obj = {};
          obj.price = '0.000';
         obj.name='';
         obj.num=0;
         obj.total_price='0.00';
            this.tableData.push(obj)
            console.log(this.tableData);
        },
    }
}
</script>
<style lang="scss" scoped>
.top_order{
    display: flex;
    flex-wrap: wrap;
    margin-top: 15px;

    .order_select{
        width: 600px;
    }
}
.before_table{
    display: flex;
    flex-direction: row-reverse;
    margin-bottom:15px
}
.modal_content {
  
  overflow: hidden;
  overflow-y: auto;
  .modal_content_left {
      width: 15%;
  }
  .modal_content_center {
    
    .modal_content_center_top {
      display: flex;
      flex-wrap: wrap;
    }
    .modal_content_center_body {
      padding-top: 20px;
    }
    .modal_content_center_footer {
      display: flex;
      justify-content: center;
      padding-top: 20px;
    }
  }
 
}
</style>