<template>
  <div>
    <div class="borderless">
      <div class="customer-head">
        <div class="customer-back">
          <el-button type="danger" style="border: none;background: none;color: red" icon="el-icon-arrow-left" @click="backToList">
            返回列表
          </el-button>
        </div>
        <div class="add-customer-btn">
          <el-button v-if="form.status == 1" size="small" @click="disabled(0)">
            启用
          </el-button>
          <el-button v-if="form.status == 0" size="small" @click="disabled(1)">
            禁用
          </el-button>
          <el-button type="primary" size="small" @click="editCustomer">
            保存数据
          </el-button>
        </div>
      </div>
      <trade-card title="基础资料" style="margin-top: 60px">
        <avue-form ref="form" class="trading-form" v-model="form" :option="option">
          <template slot="goodsTypeId">
            <div style="display:flex;">
              <avue-cascader :emit-path="false" check-strictly :show-all-levels="false" v-model="form.goodsTypeId" placeholder="请选择产品分类" :dic="goodsTypeList" :props="props"></avue-cascader>
              <i class="el-icon-circle-plus-outline" style="font-size:18px;line-height: 32px;margin-left:4px" @click="goodsTypeVisible = true"></i>
            </div>
          </template>
          <template slot="unit">
            <div style="display:flex;">
              <avue-select v-model="form.unit" filterable placeholder="请选择单位" :dic="unitList" :props="props2"></avue-select>
              <i class="el-icon-circle-plus-outline" style="font-size:18px;line-height: 32px;margin-left:4px" @click="$refs.dictbiz.open()"></i>
            </div>
          </template>
          <template slot="whether">
            <el-switch v-model="form.whether" active-text="是" inactive-text="否" active-value="1" inactive-value="0" @change="whetherChange"/>
          </template>
            <template slot="whetherIntegral">
                <el-switch v-model="form.whetherIntegral" active-text="是" inactive-text="否" active-value="1" inactive-value="0" @change="whetherIntegralChange"/>
            </template>
        </avue-form>
      </trade-card>
      <trade-card title="库存管理" v-loading="loadingBtn">
        <avue-crud ref="crud" :option="optionList" :data="data" :table-loading="loading" @saveColumn="saveColumn"
                   @resetColumn="resetColumn" :cell-style="cellStyle" @row-update="rowUpdate"  @row-save="rowSave">
          <!--<template slot="headerSerial">-->
          <!--  <el-button type="primary" icon="el-icon-plus" size="mini" @click.stop="addRow"-->
          <!--             :disabled="detailData.status == 1" circle></el-button>-->
          <!--</template>-->
          <template slot="storageIdHeader" slot-scope="{column}">
            <span style="color: #409EFF;cursor: pointer" @click.stop="storageVisible = true">仓库</span>
          </template>
          <template slot="menu" slot-scope="{ row, index }">
            <el-button size="small" type="text" @click="rowCell(row, index)">{{ row.$cellEdit ? "保存" : "修改" }}
            </el-button>
            <!--<el-button size="small" type="text" @click="rowDel(row, index)">删除</el-button>-->
          </template>
        </avue-crud>
      </trade-card>
      <containerTitle title="主图附件"></containerTitle>
      <c-upload :data="filesList" display deleteUrl="/api/blade-client/goodsfiles/delete" :enumerationValue="160" />
      <el-dialog title="设置产品分类" v-dialogDrag :visible.sync="goodsTypeVisible" class="avue-dialog"
        width="80%" append-to-body @closed="goodsTypeClosed">
        <span>
          <!-- <avue-form :key="reload" ref="goodsType" v-model="form2" :option="option2" style="margin-top:20px"></avue-form> -->
          <goods-type></goods-type>
        </span>
        <div class="avue-dialog__footer">
          <el-button @click="goodsTypeVisible = false" size="mini">取 消</el-button>
          <el-button @click="saveGoodstype" type="primary" size="mini">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog title="添加仓库" v-dialogDrag :visible.sync="storageVisible" class="avue-dialog avue-dialog--top" width="30%" append-to-body @closed="storageClosed">
        <span>
          <avue-form :key="reload2" ref="storage" v-model="form3" :option="option3" style="margin-top:20px"></avue-form>
        </span>
        <div class="avue-dialog__footer">
          <el-button @click="storageVisible = false" size="mini">取 消</el-button>
          <el-button @click="savestorage" type="primary" size="mini">确 定</el-button>
        </div>
      </el-dialog>
      <dictbiz-dialog ref="dictbiz" title="添加单位" code="unit" parentId="1585962784498225154" @closed="getAllWorkDicts"></dictbiz-dialog>
    </div>
  </div>
</template>

<script>
import { getGoodstype, getDetails, goodsTypesubmit, getStoragetype, submit, itemRemove, disabled, getStoragelist, storagesubmit } from "@/api/basicData/product";
import { optionList } from "./js/optionList";
import goodsType from '@/components/goodsType/index'
import {getList} from "@/api/basicData/client";
import {getList as getListpp } from "@/api/tirePartsMall/basicData/brandPage";
import {listAllP} from "../../api/tirePartsMall/basicData/listingManagement";
export default {
  name: "index",
  data() {
    return {
      loadingBtn: false,
      goodsTypeVisible: false,
      storageVisible: false,
      form: {},
      form2: {},
      form3: {},
      data: [],
      option: {
        menuBtn: false,
        labelWidth: 100,
        column: [
          {
            label: "名称",
            prop: "cname",
            span: 16,
            rules: [{
              required: true,
              message: "请输入通知标题",
              trigger: "blur"
            }]
          },
          {
            label: "产品分类",
            prop: "goodsTypeId",
            type: 'select',
            dicData: [],
            props: {
              label: 'detailedAddress',
              value: 'detailedAddress'
            },
            filterable: true,
            span: 8,
            rules: [{
              required: true,
              message: "请输入通知标题",
              trigger: "blur"
            }]
          },
          {
            label: "单位",
            prop: "unit",
            type: "select",
            props: {
              label: "dictValue",
              value: "dictValue"
            },
            dicUrl: "/api/blade-system/dict-biz/dictionary?code=unit",
            span: 8,
            rules: [{
              required: true,
              message: "请输入通知标题",
              trigger: "blur"
            }]
          },
          {
            label: "零售价",
            prop: "standardPrice",
            type: 'number',
            minRows: 0,
            controls: false,
            span: 8,
            rules: [{
              required: true,
              message: "请输入通知标题",
              trigger: "blur"
            }]
          },
          {
            label: "售价1",
            prop: "wholesalePrice",
            type: 'number',
            minRows: 0,
            controls: false,
            span: 8,
            rules: [{
              required: true,
              message: "请输入通知标题",
              trigger: "blur"
            }]
          },
          {
            label: "售价2",
            prop: "repairDepotPrice",
            type: 'number',
            minRows: 0,
            controls: false,
            span: 8,
            rules: [{
              required: true,
              message: "请输入通知标题",
              trigger: "blur"
            }]
          },
          {
            label: "售价3",
            prop: "storePrice",
            type: 'number',
            minRows: 0,
            controls: false,
            span: 8,
            rules: [{
              required: true,
              message: "请输入通知标题",
              trigger: "blur"
            }]
          },
          {
            label: "售价4",
            prop: "price",
            type: 'number',
            minRows: 0,
            controls: false,
            span: 8,
            rules: [{
              required: true,
              message: "请输入通知标题",
              trigger: "blur"
            }]
          },
          {
            label: "进货价",
            prop: "purchasePrice",
            type: 'number',
            minRows: 0,
            controls: false,
            span: 8,
            rules: [{
              required: true,
              message: "请输入通知标题",
              trigger: "blur"
            }]
          },
          {
            label: "特价",
            prop: "specialOffer",
            type: 'number',
            minRows: 0,
            controls: false,
            span: 8,
            rules: [{
              required: true,
              message: "请输入通知标题",
              trigger: "blur"
            }]
          },
          {
            label: "销售数量",
            prop: "salesVolumes",
            type: 'number',
            minRows: 0,
            controls: false,
            span: 8
          },
          {
            label: "标签",
            prop: "label",
            type: 'checkbox',
            dataType: "string",
            props: {
              label: "dictValue",
              value: "dictValue"
            },
            dicUrl: "/api/blade-system/dict-biz/dictionary?code=label",
            span: 8,
          },
          {
            label: "是否管理批次号",
            prop: "whether",
            labelWidth:120,
            span: 8,
            rules: [{
              required: true,
              message: "请输入通知标题",
              trigger: "blur"
            }]
          },
            {
                label: "是否为积分商品",
                prop: "whetherIntegral",
                labelWidth:120,
                span: 8,
                rules: [{
                    required: true,
                    message: "请输入通知标题",
                    trigger: "blur"
                }]
            },
            {
                label: "门店积分",
                prop: "storeIntegral",
                type: 'number',
                minRows: 0,
                controls: false,
                disabled:true,
                span: 6,
                value:0,
                rules: [{
                    pattern:/^[+]{0,1}(\d+)$/,
                    message:"必须为正整数",
                    trigger:"blur"
                }]
            },
            {
                label: "推荐人积分",
                prop: "referenceIntegral",
                type: 'number',
                minRows: 0,
                controls: false,
                disabled:true,
                span: 6,
                value:0,
                rules: [{
                    pattern:/^[+]{0,1}(\d+)$/,
                    message:"必须为正整数",
                    trigger:"blur"
                }]
            },
            {
                label: "业务员积分",
                prop: "salesmanIntegral",
                type: 'number',
                minRows: 0,
                controls: false,
                disabled:true,
                span: 6,
                value:0,
                rules: [{
                    pattern:/^[+]{0,1}(\d+)$/,
                    message:"必须为正整数",
                    trigger:"blur"
                }]
            },
            {
                label: "商品积分",
                prop: "integral",
                type: 'number',
                minRows: 0,
                controls: false,
                disabled:true,
                span: 6,
                value:0,
                rules: [{
                    pattern:/^[+]{0,1}(\d+)$/,
                    message:"必须为正整数",
                    trigger:"blur"
                }]
            },
            {
                label: "厂家",
                prop: "corpId",
                type: "select",
                props: {
                    label: "cname",
                    value: "id"
                },
                dicData: [],
                span: 6,
                change:(val)=>{
                    for(let item of val.column.dicData) {
                        if (val.value == item.id) {
                            this.form.corpName = item.cname
                            break;
                        }
                    }
                }
            },
            // {
            //     label: "采购日期",
            //     prop: "exitDate",
            //     type: "date",
            //     format: "yyyy-MM-dd",
            //     valueFormat: "yyyy-MM-dd 00:00:00",
            //     span: 6,
            // },
            {
                label: "规格",
                prop: "specs",
                span: 6,
            },
            {
                label: "品牌",
                prop: "brandId",
                type: "select",
                props: {
                    label: "cname",
                    value: "id"
                },
                dicData: [],
                span: 6,
                change:(val)=>{
                    for(let item of val.column.dicData) {
                        if (val.value == item.id) {
                            this.form.brand = item.cname
                            break;
                        }
                    }
                }
            },
            {
                label: "功能分类",
                prop: "categoryitemList",
                type: "select",
                multiple:true,
                props: {
                    label: "cname",
                    value: "id"
                },
                dicUrl: "/api/blade-sales-part/brandDesc/listAll?type=GN",
                span: 6,
            },
          {
            label: "备注",
            prop: "remarks",
            type: "textarea",
            minRows: 3,
            span: 24,
          }
        ]
      },
      option2: {
        menuBtn: false,
        labelWidth: 80,
        column: [
          {
            label: "分类名称",
            prop: "cname",
            rules: [
              {
                required: true,
                message: "",
                trigger: "blur"
              }
            ],
            span: 24,
          },
          {
            label: "上级类型",
            prop: "parentId",
            dicData: [],
            type: "tree",
            props: {
              label: "title",
              value: "id"
            },
            span: 24,
          }
        ]
      },
      option3: {
        menuBtn: false,
        labelWidth: 80,
        column: [
          {
            label: "仓库名称",
            prop: "cname",
            rules: [
              {
                required: true,
                message: "",
                trigger: "blur"
              }
            ],
            span: 24,
          },
          {
            label: "仓库编码",
            prop: "code",
            rules: [
              {
                required: true,
                message: "",
                trigger: "blur"
              }
            ],
            span: 24,
          },
          {
            label: "上级类型",
            prop: "parentId",
            dicData: [],
            type: "tree",
            props: {
              label: 'cname',
              value: 'id'
            },
            span: 24,
          }
        ]
      },
      filesList: [],
      props: {
        label: 'title',
        value: 'value'
      },
      props2: {
        label: 'dictValue',
        value: 'dictValue'
      },
      goodsTypeList: [],
      unitList: [],
      optionList: {},
        // admin 权限
        roleNameqx:[]
    };
  },
  components: {
    goodsType
  },
  props: {
    detailData: {
      type: Object
    }
  },
  async created() {
    this.optionList = await this.getColumnData(
      this.getColumnName(218),
      optionList
    );
    if (await this.detailData.goodsTypeId){
      this.form.goodsTypeId = this.detailData.goodsTypeId;
    }
    if (this.detailData.id) {
      this.getDetail(this.detailData.id);
    }else {
        let arr = localStorage.getItem('roleName').split(',')
        // this.whetherIntegralChange(this.form.whetherIntegral)
        if (arr.indexOf('admin') != -1) {
            this.findObject(this.option.column, "storeIntegral").disabled = false
            this.findObject(this.option.column, "referenceIntegral").disabled = false
            this.findObject(this.option.column, "salesmanIntegral").disabled = false
            this.findObject(this.option.column, "integral").disabled = false
        }
    }
    if (this.detailData.status == 1) {
      this.option.disabled = true;
    }

    // 获取供应商数据
      this.getListfun()
      this.getListppfun()

    this.getAllWorkDicts()
  },
  methods: {
      // 获取供应商数据
      getListfun(){
          getList(1,20, {corpType:'GYS'}).then(res=>{
              console.log(res.data)
              this.findObject(this.option.column, "corpId").dicData = res.data.data.records
          })
      },
      // 获取品牌数据
      getListppfun(){
          getListpp({
              current: 1,
              size: 20,
          }).then(res=>{
              this.findObject(this.option.column, "brandId").dicData = res.data.data.records
          })
      },

    getAllWorkDicts() {
      getGoodstype().then(res => {
        this.goodsTypeList = res.data.data;
        this.findObject(this.option2.column, "parentId").dicData = res.data.data;
      });
      getStoragelist().then(res => {
        this.findObject(this.optionList.column, "storageId").dicData = res.data;
        this.findObject(this.option3.column, "parentId").dicData = res.data;
      });
      this.getWorkDicts("unit").then(res => {
        this.unitList = res.data.data;
      });
    },
    cellStyle() {
      return "padding:0;height:40px;";
    },
    addRow() {
      this.data.push({$cellEdit: true})
    },
    rowCell(row, index) {
      this.$refs.crud.rowCell(row, index)
    },
    rowSave(form, done) {
      done()
    },
    rowUpdate(form, index, done) {
      done()
    },
    rowDel(row, index) {
      this.$confirm("确定删除数据?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        if (row.id) {
          itemRemove({ids: row.id}).then(res => {
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            this.data.splice(index, 1);
          });
        } else {
          this.$message({
            type: "success",
            message: "删除成功!"
          });
          this.data.splice(index, 1);
        }
      });
    },
    disabled(val) {
      disabled({ id: this.form.id, status: val }).then(res => {
        this.getDetail(this.detailData.id);
      })
    },
    saveGoodstype() {
      this.$refs["goodsType"].validate((valid, done) => {
        done();
        if (valid) {
          goodsTypesubmit({ ...this.form2, status: 0 }).then(res => {
            this.getAllWorkDicts()
          })
          this.goodsTypeVisible = false
        } else {
          return false;
        }
      });
    },
    savestorage() {
      // this.$refs["storage"].validate((valid, done) => {
      //   done();
      //   if (valid) {
      //     storagesubmit({ ...this.form3, status: 0 }).then(res => {
      //       this.getAllWorkDicts()
      //     })
      //     this.storageVisible = false
      //   } else {
      //     return false;
      //   }
      // });
      this.getAllWorkDicts()
      this.goodsTypeVisible = false
    },
    goodsTypeClosed() {
      // this.reload = Math.random();
      // this.form2 = this.$options.data().form2
    },
    storageClosed() {
      this.reload2 = Math.random();
      this.form3 = this.$options.data().form3
    },
    getDetail(id) {
      this.loadingBtn = true
      getDetails({ goodsId: id })
        .then(res => {
          this.form = res.data.data;
          this.form.categoryitemList = this.form.categoryitemId?this.form.categoryitemId.split(','):'';

          this.data = res.data.data.stockGoodsList;
          this.filesList = res.data.data.filesList

            // 判断是否是admin 权限
            this.roleNameqx = localStorage.getItem('roleName').split(',')
            let arr = localStorage.getItem('roleName').split(',')
            // this.whetherIntegralChange(this.form.whetherIntegral)
            if (arr.indexOf('admin') != -1 && res.data.data.whetherIntegral == 0) {
                this.findObject(this.option.column, "storeIntegral").disabled = false
                this.findObject(this.option.column, "referenceIntegral").disabled = false
                this.findObject(this.option.column, "salesmanIntegral").disabled = false
                this.findObject(this.option.column, "integral").disabled = false
            }

          this.whetherChange(res.data.data.whether)
        })
        .finally(() => {
          this.loadingBtn = false;
        });
    },
      // 是否为积分商品的change事件
      whetherIntegralChange(val){
          console.log(val,557)
          if (this.form.whetherIntegral == 1) {
              // disabled:true,
              this.findObject(this.option.column, "storeIntegral").disabled = true
              this.findObject(this.option.column, "referenceIntegral").disabled = true
              this.findObject(this.option.column, "salesmanIntegral").disabled = true
              this.findObject(this.option.column, "integral").disabled = true

              // 四个售价变成正整数
              this.findObject(this.option.column, "wholesalePrice").rules[0].pattern = /^[+]{0,1}(\d+)$/
              this.findObject(this.option.column, "repairDepotPrice").rules[0].pattern = /^[+]{0,1}(\d+)$/
              this.findObject(this.option.column, "storePrice").rules[0].pattern = /^[+]{0,1}(\d+)$/
              this.findObject(this.option.column, "price").rules[0].pattern = /^[+]{0,1}(\d+)$/

          }else if (this.form.whetherIntegral == 0 && this.roleNameqx.indexOf('admin') == -1) {
              this.findObject(this.option.column, "storeIntegral").disabled = false
              this.findObject(this.option.column, "referenceIntegral").disabled = false
              this.findObject(this.option.column, "salesmanIntegral").disabled = false
              this.findObject(this.option.column, "integral").disabled = false
          }

      },
      // 是否管理批次号的change事件
    whetherChange(val){
      console.log(val)
      if (val == 0||val==null) {
          this.findObject(this.optionList.column, "lotNo").hide = true
          this.findObject(this.optionList.column, "lotNo").showColumn = false
        } else {
          this.findObject(this.optionList.column, "lotNo").hide = false
          this.findObject(this.optionList.column, "lotNo").showColumn = true
        }
    },
    //修改提交触发
    editCustomer() {
      this.$refs["form"].validate((valid, done) => {
        done();
        if (valid) {
          this.loadingBtn = true;
          var categoryitemId = '';
          var categoryitem = '';
          var categoryitemList = this.form.categoryitemList
          for (let key in categoryitemList) {

            if (categoryitemList.length - 1 != key) {
              categoryitemId += categoryitemList[key]
              categoryitemId += ','
            } else {
              categoryitemId += categoryitemList[key]
            }
          }

          var data = {}
          var obj2 = new Map();
          var params = { type : 'GN'}
          listAllP(params).then(res => {
            data = res.data.data
            obj2 = new Map();
            for (let datum of data) {
              obj2.set(datum.id, datum.cname)
            }
            for (let key in categoryitemList) {
              var id = categoryitemList[key]
              if (categoryitemList.length -1 > key) {
                categoryitem += obj2.get(id)
                categoryitem += ','
              } else {
                categoryitem += obj2.get(id)
              }
            }

            this.form.categoryitemId = categoryitemId;
            this.form.categoryitem = categoryitem;

            submit({
              ...this.form,
              code: this.form.cname,
              type: 0,
              stockGoodsList: this.data,
              filesList: this.filesList
            }).then(res => {
              this.$message.success("保存成功");
              this.form = res.data.data;
              this.data = res.data.data.stockGoodsList;
              this.filesList = res.data.data.filesList;
              setTimeout(() => {
                this.backToList()
              }, 1000);
            }).finally(() => {
              this.loadingBtn = false;
            });
          })
        } else {
          return false;
        }
      });
    },
    async saveColumn() {
      const inSave = await this.saveColumnData(
        this.getColumnName(218),
        this.optionList
      );
      if (inSave) {
        this.$nextTick(() => {
          this.$refs.crud.doLayout();
        });
        this.$message.success("保存成功");
        //关闭窗口
        this.$refs.crud.$refs.dialogColumn.columnBox = false;
      }
    },
    async resetColumn() {
      this.optionList = optionList;
      const inSave = await this.delColumnData(
        this.getColumnName(218),
        optionList
      );
      if (inSave) {
        this.$nextTick(() => {
          this.$refs.crud.doLayout();
        });
        this.getAllWorkDicts()
        this.$message.success("重置成功");
        this.$refs.crud.$refs.dialogColumn.columnBox = false;
      }
    },
    //返回列表
    backToList() {
      this.$emit("goBack");
    }
  },
};
</script>

<style lang="scss" scoped>
.trading-form ::v-deep .el-form-item {
  margin-bottom: 8px !important;
}

::v-deep .el-dialog__body {
  padding: 0px 20px 15px 20px;
}

::v-deep .el-form-item__error {
  display: none !important;
}

.img-form ::v-deep .el-form-item {
  height: 150px;
  line-height: 150px;
  margin-bottom: 8px !important;
}

.img-form ::v-deep .avue-upload__icon {
  font-size: 20px;
  width: 150px;
  height: 150px;
  line-height: 150px;
}

::v-deep .el-table .cell {
  padding: 0 2px !important;
}

::v-deep .avue-crud .el-table .el-form-item__label {
  left: -1px;
}

.addressTabs {
  display: flex;
  justify-content: center;

  span {
    width: 100px;
    font-size: 18px;
    font-weight: 600;
    text-align: center;
  }
}
</style>
