<template>
  <div class="app-container">
    <el-card class="box-card">
      <div class="clearfix">
        <span class="left-text">我的供应商</span>
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-plus"
          style="float: right"
          @click="handleAdd()"
          >新增</el-button
        >
      </div>
      <!-- 分组表格 -->
      <el-table
        :data="tableData"
        :height="tableHeight"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="title" label="供货商名称"> </el-table-column>
        <el-table-column prop="operator_num" label="供应商编号">
        </el-table-column>
        <!-- <el-table-column prop="category_name" label="行业"> </el-table-column> -->
        <el-table-column prop="contacts" label="联系人"> </el-table-column>
        <el-table-column prop="contacts_phone" label="联系电话">
        </el-table-column>
        <el-table-column prop="end_time" label="终止时间" width="180px">
          <template slot-scope="scope">
            <div>
              {{ timeFormatter(scope.row.end_time) }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <div class="dotColorGreen" v-if="scope.row.status == 0"></div>
            <div class="dotColorRed" v-if="scope.row.status == 1"></div>
            {{ statusFormatter(scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
              >编辑
            </el-button>
            <el-button
              size="mini"
              type="text"
              @click="handleDelete(scope.row)"
              style="color: red"
              >删除
            </el-button>
            <!-- <el-divider direction="vertical"></el-divider> -->
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="footer_pagination">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[20, 40, 60, 80, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
    <!-- 新增或修改提示框 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      center
      :append-to-body="true"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      @close="clearPayform"
      width="40%"
    >
      <div style="width: 100%; margin: 0 auto">
        <el-form
          :model="editForm"
          ref="editForms"
          :rules="editFormRules"
          :label-position="labelPosition"
          label-width="150px"
          center
          size="mini"
        >
          <el-form-item label="供应商名称：" prop="title" inline-message="true">
            <el-input
              v-model.trim="editForm.title"
              style="width: 80%"
              placeholder="请输入供应商名称"
            ></el-input>
          </el-form-item>
          <!-- <el-form-item label="所属行业：" :rules="[{required: true,message:'请输入内容',trigger:'blur'}]">
            <el-cascader
              v-model="category"
              :props="propsOptions"
              style="width: 80%"
              @expand-change="getOpen"
              @change="closeCascader"
              ref="ssqCascader"
            ></el-cascader>
          </el-form-item> -->
          <el-form-item label="联系人：" prop="contacts" inline-message="true">
            <el-input
              v-model.trim="editForm.contacts"
              style="width: 80%"
              placeholder="请输入供应商联系人"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="联系电话："
            prop="contacts_phone"
            inline-message="true"
          >
            <el-input
              v-model.trim="editForm.contacts_phone"
              style="width: 80%"
              placeholder="请输入供应商联系电话"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="终止时间："
            prop="end_time"
            inline-message="true"
          >
            <el-date-picker
              v-model="editForm.end_time"
              type="datetime"
              style="width: 80%"
              unaLink-panels
              value-format="timestamp"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="状态：" prop="status" inline-message="true">
            <el-radio-group v-model="editForm.status">
              <el-radio :label="0">启用</el-radio>
              <el-radio :label="1">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="mini">取 消</el-button>
        <el-button
          type="primary"
          size="mini"
          @click="closeDialogVisible('editForms')"
          >提交</el-button
        >
      </span>
    </el-dialog>
    <!-- 删除弹窗 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogDelete"
      center
      :close-on-click-modal="false"
      width="30%"
    >
      <div style="text-align: center; margin: 0 auto">
        <p>确定要删除该供应商吗？删除后，将无法与商品对应</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogDelete = false" size="mini">取 消</el-button>
        <el-button type="primary" size="mini" @click="closeDialogDelete()"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { NewGetCategoryData } from "@/api/module/goods";
import {
  goodsOperatorList,
  deleteOperator,
  operatorInfo,
  updateOperator,
} from "@/api/system/supplier";
import { dateFormat } from "@/utils";
export default {
  name: "supplier",
  data() {
    // 手机号码格式校验
    let checkTel = (rule, value, callback) => {
      const reg = /^1[3456789]\d{9}$/;
      if (value === "") {
        callback(new Error("手机号码不能为空"));
      } else if (!reg.test(value)) {
        callback(new Error("手机号码格式不对,请重新输入"));
      } else {
        callback();
      }
    };
    return {
      fullHeight: 0,
      tableHeight: 0,
      total: 0,
      currentPage: 1,
      pageSize: 20,
      code: 0, //删除的供应商id
      tableData: [],
      labelPosition: "right",
      //新增和修改提示语
      title: "",
      operation: 1, //1添加 2 修改
      category: [], //表单行业数据
      //新增表单内容
      editForm: {
        title: "", //供应商名称
        contacts: "", //联系人
        contacts_phone: "", //联系电话
        end_time: "", //终止时间
        status: 0, //状态
      },
      //表单验证
      editFormRules: {
        title: [
          { required: true, message: "请输入供应商名称", trigger: "blur" },
        ],
        contacts: [
          { required: true, message: "请输入联系人", trigger: "blur" },
        ],
        contacts_phone: [
          { required: true, validator: checkTel, trigger: "blur" },
        ],
        end_time: [
          { required: true, message: "请输入终止时间", trigger: "blur" },
        ],
        status: [
          { required: true, message: "供应商名称不能为空", trigger: "blur" },
        ],
      },
      //   所属行业下拉框
      propsOptions: {
        expandTrigger: "click",
        lazy: true,
        checkStrictly: true, // 父子不想关联
        lazyLoad: this.lazyLoad,
        value: "id",
        label: "title",
        leaf: "leaf",
      },
      jobList: [],
      isOpen: false,
      arrList: [],
      //新增表单弹框
      dialogVisible: false,
      //删除弹框
      dialogDelete: false,
    };
  },
  created() {
    this.$nextTick(() => {
      this.fullHeight =
        document.getElementsByClassName("box-card")[0].clientHeight;
    });
    this.getGoodsOperatorList();
  },
  watch: {
    fullHeight(val) {
      let formHeight =
        document.getElementsByClassName("clearfix")[0].clientHeight;
      this.tableHeight = val - formHeight - 120;
    },
  },
  methods: {
    //新增分组
    handleAdd() {
      this.editForm.title = "";
      this.editForm.contacts = "";
      this.editForm.contacts_phone = "";
      this.editForm.end_time = "";
      this.editForm.status = 0;
      this.dialogVisible = true;
      this.title = "新增供应商";
      this.operation = 1;
    },
    //删除分组
    handleDelete(val) {
      this.code = val.id;
      this.dialogDelete = true;
    },
    //修改分组
    handleUpdate(val) {
      this.title = "编辑供应商";
      this.operation = 2;
      this.code = val.id;
      let obj = {
        id: val.id,
      };
      operatorInfo(obj).then((res) => {
        if (res.code == 1) {
          this.editForm = res.data;
          this.editForm.end_time = res.data.end_time * 1000;
          this.dialogVisible = true;
        } else {
          this.$message({
            type: "error",
            message: res.message,
          });
        }
      });
    },
    //删除提示框
    closeDialogDelete() {
      let obj = {
        id: this.code,
      };
      deleteOperator(obj).then((res) => {
        if (res.code == 1) {
          this.getGoodsOperatorList();
          this.$message({
            type: "success",
            message: "删除成功",
          });
          this.dialogDelete = false;
        } else {
          this.$message({
            type: "error",
            message: res.message,
          });
          this.dialogDelete = false;
        }
      });
    },
    //新增或修改弹框确定回调
    closeDialogVisible(editForms) {
      //   let ssqLabelList = this.$refs["ssqCascader"].getCheckedNodes()[0];
      this.$refs[editForms].validate((valid) => {
        if (valid) {
          let obj = {};
          obj["operation"] = this.operation;
          // obj["category_id"] = ssqLabelList.data.id;
          // obj["category_name"] = ssqLabelList.data.title;
          obj["title"] = this.editForm.title;
          obj["contacts"] = this.editForm.contacts;
          obj["contacts_phone"] = this.editForm.contacts_phone;
          obj["end_time"] = new Date(this.editForm.end_time).getTime() / 1000;
          obj["status"] = this.editForm.status;
          if (this.title == "新增供应商") {
            updateOperator(obj).then((res) => {
              if (res.code == 1) {
                this.$message({
                  type: "success",
                  message: "添加成功",
                });
                this.getGoodsOperatorList();
                this.dialogVisible = false;
              } else {
                this.$message({
                  type: "error",
                  message: res.message,
                });
              }
            });
          } else if (this.title == "编辑供应商") {
            obj["id"] = this.code;
            updateOperator(obj).then((res) => {
              if (res.code == 1) {
                this.$message({
                  type: "success",
                  message: "编辑成功",
                });
                this.getGoodsOperatorList();
                this.dialogVisible = false;
              } else {
                this.$message({
                  type: "error",
                  message: res.message,
                });
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    //级联菜单懒加载
    // getOpen(val) {
    //   if (this.isOpen) {
    //     this.arrList.push(val);
    //   }
    //   this.category = val;
    //   try {
    //     this.arrList.forEach((item) => {
    //       if (item[1] == val[1]) {
    //         throw new Error("End Loop");
    //       } else {
    //       }
    //     });
    //   } catch {}
    // },
    // lazyLoad(node, resolve) {
    //   this.category = [];
    //   this.getArea(node, resolve);
    // },
    // getArea(node, resolve) {
    //   const level = node.level;
    //   let limboNode = {};
    //   if (level === 0) {
    //     limboNode = { parent_id: 0 };
    //   }
    //   if (level === 1) {
    //     limboNode = { parent_id: node.value };
    //   }
    //   if (level === 2) {
    //     limboNode = { parent_id: node.value };
    //   }

    //   NewGetCategoryData(limboNode).then((res) => {
    //     let result = {};
    //     result = res.data;
    //     if (level === 0) {
    //       result.forEach((item) => {
    //         item.value = item.id;
    //         item.label = item.label;
    //         item.children = [];
    //         item.leaf = 0; // 可以控制 是否有下级   值为true都不行，必须等于0
    //       });
    //     }

    //     if (level === 1) {
    //       for (let i = 0; i < res.data.length; i++) {
    //         if (limboNode.id === res.data[i].id) {
    //           result = res.data[i].children;
    //           break;
    //         }
    //       }
    //       result.forEach((item) => {
    //         item.value = item.id;
    //         item.label = item.label;
    //         item.children = [];
    //         //这句代码表示当点击最后一级的时候 label后面不会转圈圈 并把相关值赋值到选择器上
    //         item.leaf = 0;
    //       });
    //     }
    //     if (level === 2) {
    //       for (let i = 0; i < res.data.length; i++) {
    //         if (limboNode.id === res.data[i].id) {
    //           result = res.data[i].children;
    //           break;
    //         }
    //       }
    //       if (res.data.length == 0) {
    //         this.isOpen = true;
    //       } else {
    //         this.isOpen = false;
    //         result.forEach((item) => {
    //           item.value = item.id;
    //           item.label = item.label;
    //           item.leaf = 1;
    //         });
    //       }
    //     }
    //     resolve(result);
    //   });
    // },
    //分页查询
    handleSizeChange(val) {
      this.pageSize = val;
      this.getGoodsOperatorList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getGoodsOperatorList();
    },
    /** 一般时间 格式化 */
    timeFormatter(time) {
      if (time) {
        return dateFormat(time * 1000, "Y-m-d H:i:s");
      } else {
        return "--";
      }
    },
    statusFormatter(val) {
      if (val == 0) {
        return "正常";
      } else if (val == 1) {
        return "停用";
      }
    },
    //获取列表
    getGoodsOperatorList() {
      let obj = {
        page: this.currentPage,
        limit: this.pageSize,
      };
      goodsOperatorList(obj).then((res) => {
        if (res.code == 1) {
          this.total = res.data.count;
          this.tableData = res.data.list;
        }
      });
    },
    // 清除表单验证
    clearPayform() {
      this.editForm.title = "";
      this.editForm.category_name = "";
      this.editForm.contacts = "";
      this.editForm.contacts_phone = "";
      this.editForm.end_time = "";
      this.editForm.status = 0;
    },
    //级联菜单选中后自动关闭
    closeCascader() {
      this.$refs.ssqCascader.dropDownVisible = false;
    },
  },
};
</script>
<style scoped>
.dotColorGreen {
  display: inline-block;
  width: 6px;
  height: 6px;
  background: #23c58f;
  border-radius: 50%;
}
.dotColorRed {
  display: inline-block;
  width: 6px;
  height: 6px;
  background: #f14e4e;
  border-radius: 50%;
}
.clearfix {
  margin: 8px 0 20px 0;
}
.left-text {
  font-size: 16px;
  font-family: Microsoft YaHei;
  font-weight: bold;
  color: #333333;
  line-height: 28px;
}
/* 分页 */
.footer_pagination {
  text-align: center;
  margin-top: 15px;
}
</style>