<!--
  - Author: gn
  -->
<template>
  <div cclass="user">
    <basic-container>
      <el-row :span="24">
        <el-col :xs="24" :sm="24" :md="5" class="user__tree">
          <avue-tree :option="treeOption" :data="treeData" @node-click="nodeClick">
            <span class="el-tree-node__label" slot-scope="{ node, data }">
              <el-tooltip
                class="item"
                effect="dark"
                content="无数据权限"
                placement="right-start"
                v-if="data.isLock"
              >
                <span>
                  {{node.label}}
                  <i class="el-icon-lock"></i>
                </span>
              </el-tooltip>
              <span v-if="!data.isLock">{{node.label}}</span>
            </span>
          </avue-tree>
        </el-col>
        <el-col :xs="24" :sm="24" :md="19" class="user__main">
          <avue-crud
            ref="crud"
            :page="page"
            :permission="permissionList"
            :table-loading="tableLoading"
            :option="tableOption"
            v-model="form"
            :before-open="handleOpenBefore"
            @on-load="getList"
            :data="tableData"
            @search-change="searchChange"
            @refresh-change="refreshChange"
            @size-change="sizeChange"
            @current-change="currentChange"
            @row-update="update"
            @row-save="handleSave"
          >
            <template slot="parentIdForm">
              <avue-input-tree
                v-model="form.parentId"
                :dic="treeCustData"
                :props="defaultProps"
                placeholder="请选择所属客户"
              />
            </template>
            <template slot="menu" slot-scope="scope">
              <el-button
                type="text"
                size="small"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row,scope.index)"
              >编辑</el-button>
              <el-button
                type="text"
                size="small"
                icon="el-icon-delete"
                @click="rowDel(scope.row,scope.index)"
              >删除</el-button>
              <el-button
                type="text"
                size="small"
                icon="el-icon-menu"
                @click="handleChangePrice(scope.row,scope.index)"
              >调价</el-button>
              <el-button
                type="text"
                size="small"
                icon="el-icon-menu"
                @click="handleItem(scope.row,scope.index)"
              >账号</el-button>
            </template>
          </avue-crud>
        </el-col>
      </el-row>
    </basic-container>
    <el-dialog :visible.sync="dialogFormVisible" title="账号管理" width="90%" @close="custItemVisible">
      <avue-crud
        ref="crudItem"
        :page="itemPage"
        :data="tableCustItemData"
        :permission="permissionList"
        v-model="form2"
        @on-load="getUserList"
        :before-open="handleBeforeOpen"
        :option="tableCustOption"
        @size-change="itemSizeChange"
        @search-change="searchUserChange"
        @current-change="itemCurrentChange"
        @row-update="updateUser"
        @row-save="createUser"
        @row-del="deleteUser"
      >
        <template slot="menu" slot-scope="scope">
          <el-button
            type="text"
            size="small"
            icon="el-icon-edit"
            @click="handleUserUpdate(scope.row,scope.index)"
          >编辑</el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-delete"
            @click="deleteUser(scope.row,scope.index)"
          >删除</el-button>
        </template>
      </avue-crud>
    </el-dialog>
    <el-dialog :visible.sync="dialogFormVisiblePrice" title="调价管理" width="90%">
      <avue-crud
        :page="itemPage2"
        ref="crudGoods"
        :data='goodsdata'
        :option="goodsCustOption"
        @row-update="updateGoods"
        v-model="form3"
        :table-loading="goodsLoading"
        @search-change="goodsSearchChange"
      >
      <template slot="menuLeft">
          <el-button
            type="primary"
            size="small"
            icon="el-icon-plus"
            @click="handleAddGoods"
          >添加</el-button>
        </template>
        <template slot="menu" slot-scope="scope">
          <el-button
            type="text"
            size="small"
            icon="el-icon-edit"
            @click="handleGoodsUpdate(scope.row,scope.index)"
          >编辑</el-button>
          <el-button
            type="text"
            size="small"
            icon="el-icon-delete"
            @click="deleteGoods(scope.row,scope.index)"
          >删除</el-button>
        </template>  
      </avue-crud>
    </el-dialog>
    <!-- <el-dialog
      title="添加"
      :visible.sync="addGoodsvisible"
      width="800"
      :close-on-click-modal="false"
      append-to-body
    >
     <avue-form v-model="addGoodsForm" :option="addGoodsOption">
      <template slot="goodsTypeCode">
        <avue-select
          v-model="form.goodsTypeCode"
          placeholder="请选择商品大类"
          type="tree"
          :dic="goodsTypeList"
        ></avue-select>
      </template>

      <template slot="goodsVersion">
        <avue-select
          @change="getGoodsByVersion"
          v-model="form.goodsVersion"
          placeholder="请选择版本"
          :dic="goodsVersionList"
        ></avue-select>
      </template>

      <template slot="goodsNo">
        <avue-input-tree
          @change="goodsNoChange"
          v-model="form.goodsNo"
          placeholder="请选择商品"
          type="tree"
          :dic="goodsNoList"
        ></avue-input-tree>
      </template>

     </avue-form>
    </el-dialog> -->
    <ModalUpload ref="modalUploadRef" :custNoData='custNoData' @ok="getGoodsDataFn()"/>
  </div>
</template>

<script>
import {
  queryGoods,
  updateGoods,
  delGoodsAPI,
  fetchList,
  getObj,
  addObj,
  putObj,
  delObj,
  fetchTree
} from "@/api/baseManage/invcust";
import {
  addUserObj,
  delUserObj,
  fetchUserList,
  putUserObj
} from "@/api/admin/user";
import ModalUpload from "./modalUpload";
import { mapGetters } from "vuex";
import { checkphone } from "@/util/GnUtils";

export default {
  name: "invcust",
  data() {
    return {
      goodsdata: [],
      searchForm: {},
      addGoodsForm: {},
      url: {
        getGoodsTypeList: "/invtory/invgoodstype/getAllGoodsType",
      },
      goodsTypeList: [],
      custNoData: '',
      addGoodsOption: {
        column: [
          {
            label: "商品大类",
            prop: "goodsTypeCode",
            span: 24,
            formslot: true,
            labelWidth: 90,
            rules: [
              {
                required: true,
                message: "请选择商品大类！",
                trigger: "blur"
              }
            ]
          },
          {
            type: "select",
            formslot: true,
            label: "商品版本",
            prop: "goodsVersion",
            width: 80,
            span: 24,
            search: true,
            rules: [
              {
                required: true,
                message: "请选择商品版本",
                trigger: "blur"
              }
            ]
          },
          {
            label: "商品名",
            prop: "goodsNo",
            span: 24,
            formslot: true,
            labelWidth: 90,
            rules: [
              {
                required: true,
                message: "请选择商品！",
                trigger: "blur"
              }
            ]
          },
          {
            label: "售卖价格",
            prop: "price",
            span: 24,
            labelWidth: 90,
          }
        ]
      },
      treeOption: {
        nodeKey: "id",
        addBtn: false,
        menu: false,
        props: {
          label: "name",
          value: "id"
        }
      },
      dialogFormVisible: false,
      dialogFormVisiblePrice: false,
      addGoodsvisible: false,
      tableCustItemData: [],
      form: {},
      form2: {
        orgCode: undefined,
        custId: undefined,
        password: undefined,
        userType: "C"
      },
      form3: {},
      treeData: [],
      treeCustData: [],
      tableData: [],
      defaultProps: {
        label: "name",
        value: "id"
      },
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      itemPage: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      itemPage2: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20, // 每页显示多少条
      },
      tableLoading: false,
      goodsLoading: false,
      tableCustOption: {
        border: true,
        index: true,
        indexLabel: "序号",
        stripe: true,
        menuAlign: "center",
        searchMenuSpan: 6,
        editBtn: false,
        delBtn: false,
        align: "center",
        addBtn: false,
        column: [
          {
            fixed: true,
            label: "id",
            prop: "userId",
            span: 24,
            hide: true,
            display: false
          },
          {
            fixed: true,
            label: "用户名",
            prop: "username",
            editDisabled: true,
            search: true,
            span: 24,
            rules: [
              {
                required: true,
                message: "请输入用户名"
              },
              {
                min: 3,
                max: 20,
                message: "长度在 3 到 20 个字符",
                trigger: "blur"
              }
            ]
          },
          {
            fixed: true,
            label: "中文名",
            prop: "chinesename",
            search: true,
            span: 24,
            rules: [
              {
                required: true,
                message: "请输入中文名"
              },
              {
                min: 2,
                message: "长度大于2个字符",
                trigger: "blur"
              }
            ]
          },
          {
            label: "密码",
            prop: "password",
            type: "password",
            value: "",
            hide: true,
            span: 24,
            rules: [
              {
                min: 6,
                max: 20,
                message: "长度在 6 到 20 个字符",
                trigger: "blur"
              }
            ]
          },
          {
            label: "手机号",
            prop: "phone",
            value: "",
            span: 24,
            rules: [
              {
                min: 11,
                max: 11,
                message: "长度在 11 个字符",
                trigger: "blur"
              }
            ]
          },
          {
            label: "状态",
            prop: "lockFlag",
            type: "radio",
            slot: true,
            border: true,
            span: 24,
            rules: [
              {
                required: true,
                message: "请选择状态",
                trigger: "blur"
              }
            ],
            dicData: [
              {
                label: "有效",
                value: "0"
              },
              {
                label: "锁定",
                value: "9"
              }
            ]
          },
          {
            width: 180,
            label: "创建时间",
            prop: "createTime",
            type: "datetime",
            format: "yyyy-MM-dd HH:mm",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            editDisabled: true,
            addDisplay: false,
            span: 24
          }
        ]
      },
      goodsCustOption: {
        align: "center",
        menuWidth:140,
        height: '350',
        editBtn: false,
        delBtn: false,
        addBtn: false,
         column:[
             {
              label:'商品编号',
              prop:'goodsNo',
              //width:200,
              search:true,
              disabled:true
            }, {
              label:'商品名称',
              // width:300,
              prop:'goodsName',
              disabled:true
            }, {
              label:'商品类型',
              //width:100,
              prop:'goodsType',
              disabled:true
            }, {
              label:'标准价格',
              //width:100,
              prop:'origPrice',
              disabled:true
            }, {
              label:'售卖价格',
              //width:100,
              prop:'price',
              type: "input",
              rules: [
                {
                  required: true,
                  message: "请输入售卖价格！",
                  trigger: "blur"
                },
                {
                  pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
                  message: '请输入数字，金额输入不能小于0，最多只可保留2位小数',
                  trigger: 'blur'
                }
              ]
            }, {
              label:'创建时间',
              //width:140,
              prop:'crteTime',
              disabled:true
            }
          ]
      },
      tableOption: {
        menuPosition: "center",
        border: true,
        index: true,
        indexLabel: "序号",
        stripe: true,
        menuAlign: "center",
        align: "center",
        searchMenuSpan: 6,
        searchSpan: 6,
        searchBtn: true,
        searchShowBtn: true,
        searchIcon: true,
        searchLabelWidth: 80,
        labelWidth: 120,
        menuWidth: 250,
        searchIndex: 3,
        submitBtn: true,
        submitText: "确定",
        menuBtn: true,
        menu: true,
        addBtn: true,
        editBtn: false,
        delBtn: false,
        column: [
          {
            type: "input",
            label: "客户ID",
            prop: "custId",
            span: 24,
            hide: true,
            display: false
          },
          {
            type: "input",
            label: "客户编号",
            prop: "custNo",
            span: 24,
            hide: false,
            display: false
          },
          {
            type: "input",
            label: "客户名称",
            prop: "custName",
            span: 24,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入客户名称！",
                trigger: "blur"
              }
            ]
          },
          {
            label: "所属客户",
            prop: "parentId",
            formslot: true,
            slot: true,
            span: 24,
            hide: true,
            dataType: "number"
          },
          {
            type: "input",
            label: "联系电话",
            prop: "contactTel",
            span: 24
            // search: true,
            //rules: [
            //{
            //required: true,
            //validator: checkphone,
            //trigger: "blur"
            //}
            //]
          },
          {
            type: "input",
            label: "省",
            prop: "provinceName",
            span: 24,
            display: false,
            hide: true,
            editDisplay: true,
            addDisplay: true
          },
          {
            type: "input",
            label: "市",
            prop: "cityName",
            span: 24,
            hide: true,
            editDisplay: true,
            addDisplay: true,
            display: false
          },
          {
            type: "input",
            label: "县区",
            prop: "districtName",
            span: 24,
            hide: true,
            editDisplay: true,
            addDisplay: true,
            display: false
          },
          {
            type: "select",
            label: "省",
            prop: "province",
            span: 8,
            hide: true,
            width: "100%",
            dicUrl: `/invtory/districts/getProvince`,
            props: {
              label: "name",
              value: "code"
            },
            cascaderItem: ["city", "district"]
            //search: true
          },
          {
            type: "select",
            label: "市",
            prop: "city",
            hide: true,
            span: 8,
            width: "100%",
            dicUrl: `/invtory/districts/getChildCity?cityCode={{province}}`,
            props: {
              label: "name",
              value: "code"
            },
            cascaderItem: ["district"]
            //search: true
          },
          {
            type: "select",
            label: "县区",
            prop: "district",
            hide: true,
            span: 8,
            width: "100%",
            dicUrl: `/invtory/districts/getChildCity?cityCode={{city}}`,
            props: {
              label: "name",
              value: "code"
            }
            //search: true
          },
          {
            type: "input",
            label: "联系人",
            prop: "linkMan",
            span: 24
          },
          {
            type: "input",
            label: "联系地址",
            prop: "contactAddr",
            span: 24,
            rules: [
              {
                required: true,
                message: "请输入联系地址！",
                trigger: "blur"
              }
            ]
          },
         
          // {
          //   type: "select",
          //   label: "所属行业",
          //   width: 200,
          //   prop: "industry",
          //   dicUrl: "admin/dict/type/industry_type",
          //   span: 24
          // },
          // {
          //   type: "textarea",
          //   label: "备注",
          //   prop: "remark",
          //   span: 24
          // },
          {
            type: "input",
            label: "创建用户",
            prop: "crteUser",
            span: 24,
            hide: true,
            // search: true,
            editDisplay: false,
            addDisplay: false
          },
          {
            type: "input",
            label: "最后更新用户",
            prop: "upteUser",
            span: 24,
            hide: true,
            // search: true,
            editDisplay: false,
            addDisplay: false
          },
          {
            type: "date",
            label: "创建时间",
            prop: "crteTime",
            span: 24,
            hide: true,
            // search: true,
            // searchRange: true,
            rangeSeparator: "~",
            format: "yyyy-MM-dd HH:mm:ss",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            editDisplay: false,
            addDisplay: false
          },
          {
            type: "date",
            label: "最后更新时间",
            prop: "upteTime",
            span: 24,
            hide: true,
            // search: true,
            // searchRange: true,
            rangeSeparator: "~",
            format: "yyyy-MM-dd HH:mm:ss",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
            editDisplay: false,
            addDisplay: false
          }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(["permissions"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permissions.generator_invcust_add, true),
        delBtn: this.vaildData(this.permissions.generator_invcust_del, true),
        editBtn: this.vaildData(this.permissions.generator_invcust_edit, true)
      };
    }
  },
  components: {
    ModalUpload
  },
  created() {
    this.init();
  },
  methods: {
    async getGoodsDataFn() {
      this.goodsLoading = true
      // console.log('🈲🈲🈲', this.custIdData)
      // console.log('🈲🈲🈲', this.itemPage2)
      const res = await queryGoods({
        custNo: this.custNoData,
        currentPage: this.itemPage2.currentPage,
        pageSize: this.itemPage2.pageSize,
        total: this.itemPage2.total
      })
      this.goodsdata = res.data.data.records
      // console.log(this.goodsdata)
      this.goodsLoading = false
    },
    handleGoodsUpdate(row, index) {
      this.$refs.crudGoods.rowEdit(row, index);
      this.form3.custName = row.custName
      this.form3.goodsName = row.goodsName
      this.form3.goodsType = row.goodsType
      this.form3.origPrice = row.origPrice
      this.form3.price = row.price
      this.form3.crteTime = row.crteTime
    },
    updateGoods(row, index, done, loading) {
      updateGoods(this.form3)
        .then(() => {
          this.getGoodsDataFn();
          done();
          this.$notify.success("修改成功");
        })
        .catch(() => {
          loading();
        });
    },
    deleteGoods(row, index) {
      this.$confirm(
        "此操作将永久删除该用户(客户姓名:" + row.custName + "), 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        delGoodsAPI(row.id)
          .then(() => {
            this.goodsdata.splice(index, 1);
            this.$notify.success("删除成功");
          })
          .catch(() => {
            this.$notify.error("删除失败");
          });
      });
    },
    handleAddGoods () {
      // this.addGoodsvisible = true
      this.$refs.modalUploadRef.init();
    },
    deleteUser(row, index) {
      this.$confirm(
        "此操作将永久删除该用户(用户名:" + row.username + "), 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(() => {
        delUserObj(row.userId)
          .then(() => {
            this.list.splice(index, 1);
            this.$notify.success("删除成功");
          })
          .catch(() => {
            this.$notify.error("删除失败");
          });
      });
    },
    createUser(row, done, loading) {
      if (this.form2.phone.indexOf("*") > 0) {
        this.form2.phone = undefined;
      }
      this.form2.orgCode=this.orgCode;
      this.form2.userType='C';
      addUserObj(this.form2)
        .then(() => {
          this.getUserList(this.page);
          done();
          this.$notify.success("创建成功");
        })
        .catch(() => {
          loading();
        });
    },
    updateUser(row, index, done, loading) {
      this.form2.userType='C'; 
      if (this.form2.phone && this.form2.phone.indexOf("*") > 0) {
        this.form2.phone = undefined;
      }

      putUserObj(this.form2)
        .then(() => {
          this.getUserList(this.page);
          done();
          this.$notify.success("修改成功");
        })
        .catch(() => {
          loading();
        });
    },
    itemCurrentChange(current) {
      this.itemPage.currentPage = current;
      this.getUserList();
    },
    itemSizeChange(pageSize) {
      this.itemPage.pageSize = pageSize;
      this.getUserList(this.itemPage);
    },
    handleUserUpdate(row, index) {
      this.$refs.crudItem.rowEdit(row, index);
      row.password = undefined;
      this.form2.password = undefined;
    },
    handleBeforeOpen(done) {
      this.form2.orgCode = this.orgCode;
      this.form2.custId = this.custId;
      this.form2.userType = "C";
      this.form2.password = undefined;
      done();
    },
    // handleGoodsBeforeOpen(done) {
    //   this.form3.custName = this.goodsObj.custName
    //   this.form3.goodsName = this.goodsObj.goodsName
    //   this.form3.goodsType = this.goodsObj.goodsType
    //   this.form3.origPrice = this.goodsObj.origPrice
    //   this.form3.price = this.goodsObj.price
    //   this.form3.crteTime = this.goodsObj.crteTime
    //   done()
    // },
    handleChangePrice(row, index) {
      console.log(row, index)
      this.custNoData = row.custNo
      this.dialogFormVisiblePrice = true
      this.getGoodsDataFn()
    },
    handleItem: function(row) {
      this.orgCode = row.custNo;
      this.form2.orgCode = row.custNo;
      this.form2.userType = "C";
      this.custId = row.cusId;
      this.getUserList(this.itemPage);
    },
    getUserList(page, params) {
      this.dialogFormVisible = true;
      fetchUserList(
        Object.assign(
          {
            current: this.itemPage.currentPage,
            size: this.itemPage.pageSize
          },
          params,
          this.form2
        )
      ).then(response => {
        this.tableCustItemData = response.data.data.records;
        this.itemPage.total = response.data.data.total;
      });
    },
    searchUserChange(form, done) {
      this.itemPage.currentPage = 1;
      this.getUserList(this.itemPage,form);
      done();
    },
    custItemVisible: function() {
      this.dialogFormVisible = false;
      this.itemPage.currentPage = 1;
    },
    init() {
      fetchTree().then(response => {
        this.treeData = response.data.data;
      });
    },
    handleOpenBefore(show, type) {
      fetchTree().then(response => {
        this.treeCustData = response.data.data;
      });
      show();
    },
    nodeClick(data) {
      this.page.page = 1;
      this.getList(this.page, { custId: data.id });
    },
    getList(page, params) {
      this.tableLoading = true;
      fetchList(
        Object.assign(
          {
            current: this.page.currentPage,
            size: this.page.pageSize
          },
          params,
          this.searchForm
        )
      )
        .then(response => {
          this.tableData = response.data.data.records;
          this.page.total = response.data.data.total;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableLoading = false;
        });
    },
    rowDel: function(row, index) {
      this.$confirm(
        "是否确认删除客户姓名为 " + row.custName + " 的记录？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(function() {
          return delObj(row.custId);
        })
        .then(data => {
          this.$message.success("删除成功");
          this.init();
          this.getList(this.page);
        });
    },
    handleUpdate(row, index) {
      this.$refs.crud.rowEdit(row, index);
    },

    update: function(row, index, done, loading) {
      Object.keys(row).forEach(i => {
        if (!row[i]) {
          delete row[i];
        }
      });
      putObj(row)
        .then(data => {
          this.$message.success("修改成功");
          done();
          this.init();
          this.getList(this.page);
        })
        .catch(() => {
          loading();
        });
    },
    handleSave: function(row, done, loading) {
      Object.keys(row).forEach(i => {
        if (!row[i]) {
          delete row[i];
        }
      });
      if (row.parentId == null) row.parentId = 0;
      addObj(row)
        .then(data => {
          this.$message.success("添加成功");
          done();
          this.init();
          this.getList(this.page);
        })
        .catch(() => {
          loading();
        });
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    currentChange(current) {
      this.page.currentPage = current;
    },
    searchChange(form, done) {
      this.searchForm = form;
      this.page.currentPage = 1;
      this.getList(this.page, form);
      done();
    },
    async goodsSearchChange(form, done) {
      this.goodsLoading = true
      const res = await queryGoods({
        custNo: this.custNoData,
        goodsNo: form.goodsNo,
        currentPage: this.itemPage2.currentPage,
        pageSize: this.itemPage2.pageSize,
        total: this.itemPage2.total
      })
      this.goodsdata = res.data.data.records
      this.goodsLoading = false
      done();
    },
    refreshChange() {
      this.getList(this.page);
    }
  }

  /**handleOpenBefore(show, type) {
    window.boxType = type;
    // 查询部门树
    fetchTree().then(response => {
      this.treeCustData = response.data.data;
    });
    show();
  }**/
};
</script>
<style lang="scss">
.user {
  height: 100%;

  &__tree {
    padding-top: 3px;
    padding-right: 20px;
  }

  &__main {
    .el-card__body {
      padding-top: 0;
    }
  }
}
</style>