<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 style="margin-top: 2px">
      <el-table
        v-loading="listLoading"
        :data="saleList.results"
       border
        fit
        stripe
        highlight-current-row
      
      >
        <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">{{ 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'])"
            
              @click="handleDetail(scope)"
              >详情</el-link
            >
            
             <el-link
              v-if="scope.row.is_audited==false"
            
              @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"
       
        :rules="rule1"
      >
        <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">
    <div class="trdiv">  
     <el-transfer   v-model="sale.iproducts" :data="iproductoptions"  :titles="['未选产品', '已选产品']" right-check-change="change"></el-transfer>
    </div>

      </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,
      },
     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;
            this.iproductoptions=[];
     getiproductList({material: this.sale.product,page:0}).then((response) => {
        if (response.data) {
          response.data.forEach((item) => {
          this.iproductoptions.push({
            label: item.number+"__"+item.material_.name+"__"+(item.is_mtested==true?"已军检":"未军检") , 
            key: item.id
          })
          });
        }
     
      });
         
          
        }
       
      });
      
    },
    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;
        }
       
      });
     },
     selectproduct(selval)
    {
       this.iproductoptions=[];
     getiproductList({material:selval,page:0}).then((response) => {
        if (response.data) {
          response.data.forEach((item) => {
          this.iproductoptions.push({
            label: item.number+"__"+item.material_.name+"__"+(item.is_mtested==true?"已军检":"未军检") , 
            key: item.id
          })
          });
        }
     
      });
      
    },
  
   //成品
   getproductList() {
     this.iproductoptions=[],
      getiproductList({page:0}).then((response) => {
        if (response.data) {
          response.data.forEach((item) => {
          this.iproductoptions.push({
           label: item.number+"__"+item.material_.name+"__"+(item.is_mtested==true?"已军检":"未军检") , 
            key: item.id
          })
          });
        }
      
      });
    },



    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.iproductoptions=[];
      this.$nextTick(() => {
        this.$refs["Form"].clearValidate();
      });
    },
   
    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"].clearValidate();
      });
    },
    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 {
            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>
