<template>
  <div class="app-container">
    <el-card>
      <div>
          <el-button type="primary" icon="el-icon-plus" @click="handleCreate"
        >新增销售记录</el-button
      >
      <el-input
              v-model="listQuery.search"
              placeholder="客户名称"
              style="width: 300px"
              class="filter-item"
              @keyup.enter.native="handleFilter"
            />
            <el-button
              class="filter-item"
              type="primary"
              icon="el-icon-search"
              @click="handleFilter"
              >搜索</el-button
            >
            <el-button
              class="filter-item"
              type="primary"
              icon="el-icon-refresh-left"
              @click="resetFilter"
              >重置</el-button
            >
    </div>
    
    </el-card>
    <el-card >
      <el-table
       
        :data="saleList.results"
       border
        fit
        stripe
        highlight-current-row
        height="100"
        v-el-height-adaptive-table="{bottomOffset: 42}"
      >
        <el-table-column type="index" width="50" />
          <el-table-column label="产品名称"    show-overflow-tooltip>
          <template slot-scope="scope" v-if="scope.row.product">{{ scope.row.product_.name }}</template>
        </el-table-column>
           <el-table-column label="产品型号"  show-overflow-tooltip>
          <template slot-scope="scope" v-if="scope.row.product">{{ scope.row.product_.specification }}</template>
        </el-table-column>
         <el-table-column label="客户名称"    show-overflow-tooltip>
          <template slot-scope="scope" v-if="scope.row.customer">{{ scope.row.customer_.name }}</template>
        </el-table-column>
           <el-table-column label="订单编号"  show-overflow-tooltip>
          <template slot-scope="scope"  v-if="scope.row.order">{{ scope.row.order_.number }}</template>
        </el-table-column>
         
              <el-table-column label="合同名称"  show-overflow-tooltip>
          <template slot-scope="scope" v-if="scope.row.order_">{{ scope.row.order_.contract_.name }}</template>
        </el-table-column>

 <el-table-column label="是否审核"  >
          <template slot-scope="scope" > <el-tag v-if="scope.row.is_audited == false">否</el-tag>
              <el-tag v-else>是</el-tag></template>
        </el-table-column>

           <el-table-column>
          <template slot-scope="scope">
             <el-link
              v-if="checkPermission(['warehouse_delete'])"
            type="primary"
              @click="handleDetail(scope)"
              >详情</el-link
            >
            
             <el-link
              v-if="scope.row.is_audited==false"
            type="primary"
              @click="handleAudit(scope)"
              >审核</el-link
            >
          
            <el-link
              v-if="scope.row.is_audited==false"
              type="danger"
              @click="handleDelete(scope)"
              >删除</el-link
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="saleList.count > 0"
        :total="saleList.count"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getList"
      />
    </el-card>
    <el-dialog
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      width="60%"
      :title="dialogType === 'edit' ? '编辑销售信息' : '新增销售信息'"
    >
      <el-form
        ref="Form"
        :model="sale"
        label-width="80px"
        label-position="right"
       
      
      >
        <el-form-item label="关联订单" prop="name">
           <el-select  style="width: 100%" v-model="sale.order" @change="selectorder" placeholder="请选择">
             <el-option
                v-for="item in orderoptions"
                :key="item.id"
                :label="item.number"
               :value="item.id">
              </el-option>
          </el-select>
        </el-form-item>
       <el-form-item label="关联客户" prop="customer">
         <el-select  style="width: 100%" v-model="sale.customer" placeholder="请选择">
             <el-option
                v-for="item in customeroptions"
                :key="item.id"
                :label="item.name"
               :value="item.id">
              </el-option>
          </el-select>
          </el-form-item>
        
     
       <el-form-item label="所需产品" prop="product">
         <el-select  style="width: 100%" v-model="sale.product"  @change="selectproduct" placeholder="请选择">
             <el-option
                v-for="item in materialoptions"
                :key="item.id"
                :label="item.name"
               :value="item.id">
              </el-option>
          </el-select>
           </el-form-item>
       
  <el-form-item label="选择产品" prop="iproducts">
  
  <el-table
     
        :data="iproductoptions"
        border
        fit
        stripe
        highlight-current-row
         ref="multipleTable"
         
      >
      <el-table-column
      type="selection"
      width="55">
    </el-table-column>
        <el-table-column type="index" width="50" />
        <el-table-column label="成品编号">
          <template slot-scope="scope">{{ scope.row.number }}</template>
        </el-table-column>

        <el-table-column label="成品批次">
          <template slot-scope="scope">{{ scope.row.batch }}</template>
        </el-table-column>
          <el-table-column label="成品名称">
          <template slot-scope="scope">{{ scope.row.material_.name }}</template>
        </el-table-column>
        
        <el-table-column label="所在仓库">
          <template slot-scope="scope">{{ scope.row.warehouse_.name }}</template>
        </el-table-column>
          <el-table-column label="是否已军检">
          <template slot-scope="scope">
          

             <el-tag v-if="scope.row.is_mtested == false">未军检</el-tag>
              <el-tag v-else>已军检</el-tag></template>

        </el-table-column>
        
  
         
       
      </el-table>
      </el-form-item>   
      </el-form>


      
      <div style="text-align: right">
        <el-button type="danger" @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirm('Form')">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { createSale,getOrderList,getCustomerList,getSaleList,getOrder,deleteSale,getSale,saleAudit} from "@/api/sam";
import checkPermission from "@/utils/permission";
import { getMaterialList } from "@/api/mtm";
import {  getiproductList,} from "@/api/inm";
import { genTree } from "@/utils";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
const defaulteSale = {
  order:null,
  customer:null,
  product:null
};
export default {
  components: { Pagination },
  data() {
    return {
      sale: defaulteSale,
     saleList: {
        count: 0,
      },
      listQuery: {
        page: 1,
        page_size: 20,
      },
      iproducts:[],
     orderoptions:[],
     customeroptions:[],
     materialoptions:[],
     iproductoptions:[],
      dialogVisible: false,
      dialogType: "new",
     
    };
  },
  computed: {},
  watch: {},
  created() {
    this.getList();
  this.getCustomerLists();
 // this.getproductList();
   this.getOrderLists();
      this.getMaterialList();
  },
  methods: {
    checkPermission,
    //关联订单
    getOrderLists() {
     
      getOrderList({page:0}).then((response) => {
        if (response.data) {
          this.orderoptions = response.data;
        }
       
      });
    },
    //选择订单变化

    selectorder(selval)
    {
      getOrder(selval).then((response) => {
        if (response.data) {
          this.sale.customer = response.data.customer;
           this.sale.product = response.data.product;
             getiproductList({page:0,to_order:response.data.id}).then((response) => {
        if (response.data) {
          this.iproductoptions=response.data;
        }
      
      });
          
        }
       
      });
      
    },
    getList() {
     
      getSaleList(this.listQuery).then((response) => {
        if (response.data) {
          this.saleList = response.data;
        }
       
      });
    },
   //关联客户
     getCustomerLists() {
      
          getCustomerList({page:0,}).then((response) => {
        
          this.customeroptions = response.data;
       
      });
     
     
    },
    //选择产品
     getMaterialList()
     {
      getMaterialList({type:1,page:0}).then((response) => {
        if (response.data) {
          this.materialoptions = response.data;
        }
       
      });
     },
    
  
   //成品
  // getproductList() {
    
     // getiproductList({page:0,material__type:1}).then((response) => {
      //  if (response.data) {
      //    this.iproductoptions=response.data;
      //  }
      
    //  });
  //  },
//根据选择的产品弹出对应库里的产品
selectproduct(){
      getiproductList({page:0,material__type:1,material:this.sale.product}).then((response) => {
        if (response.data) {
          this.iproductoptions=response.data;
        }
      
      });
},


    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    resetFilter() {
      this.listQuery = {
        page: 1,
        page_size: 20,
      }
      this.getList();
    },
    handleCreate() {
      this.sale = Object.assign({}, defaulteSale);
      this.dialogType = "new";
      this.dialogVisible = true;
      this.iproducts=[];
      this.$nextTick(() => {
        this.$refs["Form"].resetFields();
        this.iproductoptions=[];
      });
    },
   
    handleEdit(scope) {
      this.sale = Object.assign({}, scope.row); // copy obj
      console.log(this.sale);
      this.dialogType = "edit";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["Form"].resetFields();
      });
    },
    handleDelete(scope) {
      this.$confirm("确认删除?", "警告", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "error",
      })
        .then(async () => {
          await deleteSale(scope.row.id);
          this.getList();
          this.$message.success("成功");
        })
        .catch((err) => {
          console.error(err);
        });
    },
   
    async confirm(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          const isEdit = this.dialogType === "edit";
          if (isEdit) {
            updateContract(this.sale.id, this.sale).then((res) => {
              if (res.code >= 200) {
                this.getList();
                this.dialogVisible = false;
                this.$message.success("成功");
              }
            });
          } else {
             
        this.$refs.multipleTable.selection.forEach((item) => {
          this.iproducts.push(
    item.id
        );
     
      });


     
         this.sale.iproducts=this.iproducts;
            createSale(this.sale).then((res) => {
              if (res.code >= 200) {
                this.getList();
                 this.dialogVisible = false;
                this.$message.success("成功");
              }
            });
          }
        } else {
          return false;
        }
      });
    },

    //销售详情
    handleDetail(scope){

          this.$router.push({name: "salesdetail", params: { id: scope.row.id }, })
    },

    //审核
    handleAudit(scope){
            saleAudit(scope.row.id).then((res) => {
        
        if (res.code >= 200) {
            
                this.$message.success("审核成功成功");
                 this.getList();
              }
      
      });
    }
  },
};
</script>
<style scoped>
.trdiv >>> .el-transfer-panel{
  width:350px;
}
.trdiv >>> .el-transfer__buttons{
  width:110px
}

</style>
