<template>
  <div>
    <Toptitle
      :title="type == 1 ? '新增客户' : type == 2 ? '编辑客户' : '查看客户'"
    >
      <slot name="titleButton">
        <Button @click="goBack" type="primary" ghost style="margin-right:10px;"
          >返回</Button
        >
        <Button
          @click="postData"
          :disabled="isChecked"
          type="primary"
          style="margin-right:10px;"
          >保存</Button
        >
      </slot>
    </Toptitle>
    <div class="top_search">
      <Form :model="formData" :label-width="100" class="top_search_form">
        <FormItem label="客户编码:">
          <Input
            type="text"
            size="small"
            v-model="formData.code"
            :disabled="isChecked"
            placeholder="请输入客户编码"
            style="width: 200px"
          />
        </FormItem>
        <FormItem label="客户分类:">
          <el-cascader
            v-model="formData.basics_custom_id"
            size="small"
            :show-all-levels="false"
            :disabled="isChecked"
            :options="cascader_list"
            :props="{
              expandTrigger: 'hover',
              children: 'sub',
              value: 'id',
              label: 'title',
              checkStrictly: true,
              emitPath: false,
            }"
            @change="handleCascaderChange"
          ></el-cascader>
        </FormItem>
        <FormItem label="客户名称:">
          <Input
            type="text"
            size="small"
            v-model="formData.title"
            :disabled="isChecked"
            placeholder="请输入客户名称"
            style="width: 200px"
          />
        </FormItem>
        <FormItem label="折扣率(%):">
          <Input
            type="text"
            size="small"
            :disabled="isChecked"
            v-model="formData.fax"
            placeholder="请输入折扣率"
            style="width: 200px"
          >
          </Input>
        </FormItem>
        <FormItem label="专营业务员:">
          <Select
            v-model="formData.service_id"
            filterable
            clearable
            :disabled="isChecked"
          >
            <Option
              v-for="item of userList"
              :key="item.id"
              :value="item.id"
              :label="item.nickname"
            ></Option>
          </Select>
        </FormItem>
        <FormItem label="超标方案:">
          <Select
            v-model="formData.overdraft_plan_id"
            filterable
            clearable
            :disabled="isChecked"
          >
            <Option
              v-for="item of overStandardList"
              :key="item.id"
              :value="item.id"
              :label="item.title"
            ></Option>
          </Select>
        </FormItem>
        <FormItem label="是否启用:">
          <i-switch v-model="formData.lockState" :disabled="isChecked" />
        </FormItem>
      </Form>
    </div>
    <div class="addBtn">
      <Button @click="handleRuleAdd()" :disabled="isChecked" type="primary"
        >新增</Button
      >
    </div>
    <Table :columns="tableColumns" max-height="550" :data="tableData" border>
      <template slot="priceSet" slot-scope="{ index }">
        <Input
          :disabled="type == 3"
          @on-focus="openKey(index)"
          clearable
          placeholder="请输入公式"
          v-model="tableData[index].formula"
        ></Input>
      </template>
      <template slot="set" slot-scope="{ index }">
        <a
          style="margin:0 5px"
          :disabled="isChecked"
          @click="handleSet(tableData[index], index, 4)"
          >删除</a
        >
        <a
          style="margin:0 5px"
          :disabled="isChecked"
          @click="handleSet(tableData[index], index, 5)"
          >设为默认</a
        >
      </template>
    </Table>
    <Modal
      v-model="showModal"
      title="选择地区"
      @on-ok="handleModalOk"
      @on-cancel="showModal = false"
    >
      <div class="modal_content">
        <Tree
          :data="treeData"
          @on-select-change="handleSelectChange"
          @on-toggle-expand="handleToggleExpand"
          children-key="sub"
          style="width:100%;"
          class="demo-tree-render"
        ></Tree>
      </div>
    </Modal>
  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// 例如：import 《组件名称》 from '《组件路径》';
import KeyBoard from "../../../components/keyboard/index";

export default {
  name: "",
  components: { KeyBoard },
  props: {},
  // import引入的组件需要注入到对象中才能使用
  data() {
    // 这里存放数据
    return {
      type: this.$route.query.type || null,
      id: this.$route.query.id || null,
      isChecked: this.$route.query.type == 3 ? true : false,
      loading: false,
      tableData: [],
      page_index: 1,
      total: 0,
      page_size: 10,
      formData: {
        lockState: true,
      },
      keyModal: false,
      tableColumns: [
        {
          title: "负责人",
          key: "service_name",
          align: "center",
          minWidth: 140,
          render: (h, params) => {
            const { row, index } = params;
            const currencyRow = this.tableData[index];
            return this.type != 3
              ? h(
                  "Input",
                  {
                    props: {
                      value: currencyRow.service_name,
                      placeholder: "请输入负责人",
                    },
                    on: {
                      "on-change": (e) => {
                        currencyRow.service_name = e.target.value;
                      },
                    },
                  },
                  currencyRow.service_name
                )
              : h("span", {}, currencyRow.service_name);
          },
        },
        {
          title: "手机号",
          key: "mobile",
          align: "center",
          minWidth: 140,
          render: (h, params) => {
            const { row, index } = params;
            const currencyRow = this.tableData[index];
            return this.type != 3
              ? h(
                  "Input",
                  {
                    props: {
                      value: currencyRow.mobile,
                      placeholder: "请输入手机号",
                    },
                    on: {
                      "on-change": (e) => {
                        currencyRow.mobile = e.target.value;
                      },
                    },
                  },
                  currencyRow.mobile
                )
              : h("span", {}, currencyRow.mobile);
          },
        },
        {
          title: "地区",
          key: "area_title",
          align: "center",
          minWidth: 120,
          render: (h, params) => {
            const { row, index } = params;
            const currencyRow = this.tableData[index];
            return this.isChecked
              ? h("span", {}, currencyRow.area_title)
              : h(
                  "a",
                  {
                    on: {
                      click: () => {
                        this.handleAreaSet(currencyRow, index);
                      },
                    },
                  },
                  currencyRow.area_title ? currencyRow.area_title : "选择地区"
                );
          },
        },
        {
          title: "详细地址",
          key: "part_id",
          align: "center",
          minWidth: 200,
          render: (h, params) => {
            const { row, index } = params;
            const currencyRow = this.tableData[index];
            return this.type != 3
              ? h(
                  "Input",
                  {
                    props: {
                      value: currencyRow.address,
                      placeholder: "请输入详细地址",
                    },
                    on: {
                      "on-change": (e) => {
                        currencyRow.address = e.target.value;
                      },
                    },
                  },
                  currencyRow.address
                )
              : h("span", {}, currencyRow.address);
          },
        },

        { title: "操作", key: "", align: "center", slot: "set", width: 200 },
      ],
      treeData: [
        {
          title: "地区分类",
          expand: 1,
          contextmenu: 1,
          id: 0,
          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: [],
      productTypeList: [],
      partsList: [],
      attrindex: null,
      userList: [],
      overStandardList: [],
      showModal: false,
      selected: null,
      currencyIndex: null,
      cascader_list: [],
    };
  },
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.axios
      .get("/api/basics_product_index")
      .then((res) => {
        this.productTypeList = res.data.data;
      })
      .catch((err) => {
        console.error(err);
      });
    // 获取用户列表
    this.axios({ method: "get", url: "/api/employee_list" })
      .then((res) => {
        this.userList = res.data;
      })
      .catch((err) => {});
    // 获取超标方案
    this.axios({ method: "get", url: "/api/overdraft_list" })
      .then((res) => {
        this.overStandardList = res.data.data;
      })
      .catch((err) => {});
    // 获取地区分类列表
    this.axios({
      method: "get",
      url: "/api/basic_area_list",
    })
      .then((res) => {
        this.treeData[0].sub = res.data;
      })
      .catch((err) => {});
    // 获取客户分类列表
    this.axios({
      method: "post",
      url: "/api/basic_custom_list",
    })
      .then((res) => {
        this.cascader_list = res.data;
      })
      .catch((err) => {});
  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.id &&
        this.axios
          .get("/api/custom_detail", { params: { id: this.id } })
          .then((res) => {
            this.tableData = res.data.list;
            this.formData = res.data.detail;
            this.formData.lockState = this.formData.lock == 1 ? true : false;
          })
          .catch((err) => {
            console.error(err);
          });
    },
    goBack() {
      this.$router.go(-1);
    },
    handleSet(row, index, type) {
      switch (type) {
        case 4:
          this.tableData.splice(index, 1);
          break;
        //设为默认  todo
        case 5:
          break;
      }
    },
    handleAreaSet(row, index) {
      this.showModal = true;
      this.currencyIndex = index;
    },
    postData() {
      this.axios({
        method: "post",
        url: "/api/custom_edit",
        data: {
          ...this.formData,
          lock: this.formData.lockState ? 1 : 0,
          detail: this.tableData,
        },
      }).then((res) => {
        if (res.code == 200) {
          this.$Message.success(res.msg);
          this.goBack();
        }
      });
    },
    handleRuleAdd() {
      const obj = { min: null, max: null, formula: null };
      this.tableData.push({});
    },
    changeProduct(row, index) {
      this.axios
        .get("/api/get_part_by_basic_product", {
          params: { basic_product_id: row.basic_product_id },
        })
        .then((res) => {
          this.partsList = res.data;
        })
        .catch((err) => {
          console.error(err);
        });
    },
    handleToggleExpand(row) {},
    handleModalOk() {
      this.tableData[this.currencyIndex].area_title = this.selected.title || "";
      this.tableData[this.currencyIndex].basic_area_id = this.selected.id || "";
      this.tableData.splice(
        this.currencyIndex,
        1,
        this.tableData[this.currencyIndex]
      );
    },
    handleSelectChange(arr, row) {
      if (row.sub.length > 0) {
        this.selected = [];
      } else {
        this.selected = row;
      }
    },
    handleCascaderChange(value) {},
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {}, // 如果页面有keep-alive缓存功能，这个函数会触发
};
</script>

<style lang="scss" scoped>
.top_search {
  padding: 20px 0;
  width: 100%;
  max-height: 150px;
  overflow: hidden;
  overflow-y: auto;
  .top_search_form {
    // width: 800px;
    // display: flex;
    // justify-content: space-around;
    /deep/ .ivu-form-item {
      display: inline-block;
      width: 300px;
    }
  }
}
.addBtn {
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
}
/deep/ .ivu-table-wrapper {
  overflow: visible;
}
/deep/.el-input {
  width: 200px;
  height: 26px;
}
/deep/.el-input__inner {
  height: 26px;
  line-height: 26px;
}
// /deep/.is-disabled {
//   background-color: #f3f3f3;
//   color: #ccc;
//   cursor: not-allowed;
// }
</style>
