<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="contractList.results"
       border
        fit
        stripe
        highlight-current-row
       height="100"
        v-el-height-adaptive-table="{bottomOffset: 50}"
      >
        <el-table-column type="index" width="50" />
        <el-table-column label="合同名称"  width="130" show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.name }}</template>
        </el-table-column>
       
        <el-table-column label="合同编号" width="130">
          <template slot-scope="scope">{{ scope.row.number }}</template>
        </el-table-column>
         <el-table-column label="合同金额（元）" width="130">
          <template slot-scope="scope">{{ scope.row.amount }}</template>
        </el-table-column>
         <el-table-column label="开票金额（元）" width="130">
          <template slot-scope="scope">{{ scope.row.invoice }}</template>
        </el-table-column>
        
          <el-table-column label="客户名称" width="130" show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.customer_.name }}</template>
        </el-table-column>
         <el-table-column label="签订日期"  width="130">
          <template slot-scope="scope">{{ scope.row.sign_date }}</template>
        </el-table-column>
       <el-table-column label="描述" width="130" show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.description }}</template>
        </el-table-column>
  <el-table-column label="创建时间"  width="160">
          <template slot-scope="scope">{{ scope.row.create_time }}</template>
        </el-table-column>
        <el-table-column
          align="center"
          label="操作"
          width="220px"
        >
          <template slot-scope="scope">
           
            <el-link
              v-if="checkPermission(['warehouse_update'])"
              @click="handleEdit(scope)"
              >编辑</el-link
            >
            <el-link
              v-if="checkPermission(['warehouse_delete'])"
              type="danger"
              @click="handleDelete(scope)"
              >删除</el-link
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="contractList.count > 0"
        :total="contractList.count"
        :page.sync="listQuery.page"
        :limit.sync="listQuery.page_size"
        @pagination="getList"
      />
    </el-card>
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType === 'edit' ? '编辑合同' : '新增合同'"
    >
      <el-form
        ref="Form"
        :model="contract"
        label-width="80px"
        label-position="right"
        :rules="rule1"
      >
        <el-form-item label="合同名称" prop="name">
          <el-input v-model="contract.name" placeholder="合同名称" />
        </el-form-item>
        <el-form-item label="合同编号" prop="number">
          <el-input v-model="contract.number" placeholder="合同编号" />
        </el-form-item>
         <el-form-item label="合同金额" prop="amount">
          <el-input v-model="contract.amount" placeholder="合同金额" />
        </el-form-item>
        <el-form-item label="开票金额" prop="invoice">
          <el-input v-model="contract.invoice" placeholder="开票金额" />
        </el-form-item>
         <el-form-item label="签订日期" prop="sign_date">
           <el-date-picker
            v-model="contract.sign_date"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            style="width: 100%"
          >
          </el-date-picker>
        </el-form-item>
         <el-form-item label="客户" prop="sign_date">
         <el-select  style="width: 100%" v-model="contract.customer" placeholder="请选择">
             <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
               :value="item.value">
              </el-option>
          </el-select>
          </el-form-item>
         <el-form-item label="描述" prop="description">
          <el-input v-model="contract.description" placeholder="描述" />
        </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 { getContractList, createContract,updateContract,deleteContract,getCustomerList } from "@/api/sam";
import checkPermission from "@/utils/permission";


import { genTree } from "@/utils";
import Pagination from "@/components/Pagination"; // secondary package based on el-pagination
const defaultecontract = {
};
export default {
  components: { Pagination },
  data() {
    return {
      contract: defaultecontract,
     contractList: {
        count: 0,
      },
      listQuery: {
        page: 1,
        page_size: 20,
      },
     options:[],
      listLoading: true,
      dialogVisible: false,
      dialogType: "new",
      rule1: {
        name: [{ required: true, message: "请输入", trigger: "blur" }],
      },
    };
  },
  computed: {},
  watch: {},
  created() {
     this.getLists();
    this.getList();
  },
  methods: {
    checkPermission,
  
    getList() {
      this.listLoading = true;
      getContractList(this.listQuery).then((response) => {
        if (response.data) {
          this.contractList = response.data;
        }
        this.listLoading = false;
      });
    },
   
     getLists() {
      
      getCustomerList({pageoff:true}).then((response) => {
        
          this.options = genTree(response.data);
       
      });
    },
   
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    resetFilter() {
      this.listQuery = {
        page: 1,
        page_size: 20,
      }
      this.getList();
    },
    handleCreate() {
      this.contract = Object.assign({}, defaultecontract);
      this.dialogType = "new";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["Form"].clearValidate();
      });
    },
   
    handleEdit(scope) {
      this.contract = Object.assign({}, scope.row); // copy obj
      this.dialogType = "edit";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["Form"].clearValidate();
      });
    },
    handleDelete(scope) {
      this.$confirm("确认删除?", "警告", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "error",
      })
        .then(async () => {
          await deleteContract(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.contract.id, this.contract).then((res) => {
              if (res.code >= 200) {
                this.getList();
                this.dialogVisible = false;
                this.$message.success("成功");
              }
            });
          } else {
            createContract(this.contract).then((res) => {
              if (res.code >= 200) {
                this.getList();
                 this.dialogVisible = false;
                this.$message.success("成功");
              }
            });
          }
        } else {
          return false;
        }
      });
    },
  },
};
</script>
