<!--
  - Author: gn
  -->
<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    :width="width"
    :close-on-click-modal="false"
    append-to-body
  >
    <avue-form ref="formRef" v-model="form" :option="formOption">

      <template slot="goodsNoList" slot-scope="{ row }" >
        <avue-select :disabled="goodsNoListDisabled" @change="changeGoodsNoList" multiple v-model="form.goodsNoList" placeholder="请选择商品类型" type="tree" :dic="goodsTypeList"></avue-select>
      </template>

      <template slot-scope="scope" slot="goods">
        <div class="goods">
          <div v-for="(item, index) in cardsData" :key="index">
            <el-card class="box-card" shadow="always">
              <div slot="header" class="clearfix">
                <span> {{ item.goodName }} :</span>
              </div>
              
              <el-row>
                <el-col :span="24">
                  <avue-crud
                    :ref="'cardTableCrud' + index"
                    :data="item.tableData"
                    :option="item.cardTableOption"
                    @row-update="addUpdate" 
                  >
                    <template slot="orderQyt" slot-scope="scope" >
                      <avue-input-number v-if="scope.row.$cellEdit" @change="orderQytChange(scope.row, scope.index)" v-model="scope.row.orderQyt" controls-position=""></avue-input-number>
                      <span v-else>{{ scope.row.orderQyt }}</span>
                    </template>

                    <template slot="goodsNo" slot-scope="scope" >
                      <avue-input-tree v-if="scope.row.$cellEdit" @change="goodsNoChange(scope.row, scope.index, index)" v-model="scope.row.goodsNo" placeholder="请选择商品名称" type="tree" :dic="item.goodsNoList"></avue-input-tree>
                      <span v-else>{{ scope.row.goodsName }}</span>
                    </template>

                    <template slot="menu" slot-scope="scope">
                      <el-button
                        v-if="!scope.row.$cellEdit"
                        type="text"
                        size="small"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row, scope.index, index)"
                      >删除</el-button>
                    </template>
                   
                  </avue-crud>
                </el-col>
              </el-row>
            </el-card>
          </div>
        </div>
      </template>
      
      <template slot-scope="scope" slot="menuForm">
        <el-button
          size="small"
          type="primary"
          icon="el-icon-check"
          :loading="btnLoading"
          @click="handleSubmit"
        >确定
        </el-button>
        <el-button
          size="small"
          icon="el-icon-delete"
          :loading="btnLoading"
          @click="handleEmpty"
        >清空
        </el-button>
        <el-button
          size="small"
          icon="el-icon-view"
          v-if="form.orderNo"
          @click="stepPlus"
        >预览
        </el-button>
        <el-button
          size="small"
          icon="el-icon-close"
          @click="close"
        >关闭
        </el-button>
      </template>
    </avue-form>
    
    <ModalView
      ref="modalViewRef"
    />

  </el-dialog>
</template>

<script>
import { GnFormMixin } from '@/util/GnFormMixin'
import { fetchList, addResult, getResult, delResult, putResult } from '@/api/commonApis'
import { getGoodsByGoodsType } from "@/api/goodManage/invgoods";
import ModalView from './modalView'

export default {
  name: 'steps',
  mixins: [GnFormMixin],
  components: {
    ModalView
  },
  props: {
    
  },
  data() {
    return {
      title: '',
      width: '80%',
      modalFlag: '',
      url: {
        getOrderNo: '/invtory/invgoodsorder/getOrderNo',
        addOne: '/invtory/invgoodsorder',
        editOne: '',
        getGoodsNoList: 'invtory/invgoods/getGoodsByGoodsType',
        getCustNoList: '/invtory/invcust/tree',
        getGoodsTypeList: '/invtory/invgoodstype/getAllGoodsType',
        getGoodsTypeColumn: '/invtory/invgoodsprop/getGoodsPropByGoodsType',
      },
      selfOption: {},
      initSelfOption: {
        printBtn: false,
        emptyBtn: false,
        submitBtn: false,
        column: [
          // {
          //   label: '',
          //   prop: 'logo',
          //   formslot: true,
          //   span: 24,
          //   labelWidth: 120, 
          // },
        ],
        group: [
          {
            icon:'el-icon-info',
            label: '基础信息',
            prop: 'baseImformation',
            column: [
              {
                label: '订单号',
                prop: 'orderNo',
                span: 12,
                disabled: true,
                placeholder: ' ',
                labelWidth: 90, 
              },
              {
                label: '客户',
                prop: 'custNo',
                span: 12,
                labelWidth: 90, 
                type: 'tree',
                dicData: [],
                props: {
                  label: "name",
                  value: "custNo",
                },
                rules: [
                  {
                    required: true,
                    message: "请选择客户！",
                    trigger: "blur",
                  },
                ],
              },
              {
                label: '商品类型',
                prop: 'goodsNoList',
                span: 12,
                formslot: true,
                labelWidth: 90, 
                // props: {
                //   label: "goodsTypeName",
                //   value: "goodsTypeNo",
                // },
                rules: [
                  {
                    required: true,
                    message: "请选择商品类型！",
                    trigger: "blur",
                  },
                ],
              },
              {
                label: '订单日期',
                prop: 'orderDate',
                type: "date",
                span: 12,
                labelWidth: 90, 
              },
              {
                label: '快递单号',
                prop: 'courierNumber',
                type: "input",
                span: 12,
                labelWidth: 90, 
              },
              {
                type: "date",
              
                label: "发货日期",
                prop: "sendGoodsDate",
                span: 12,
              },
              {
                type: "textarea",
                label: "备注",
                prop: "remark",
                span: 24,
                labelWidth: 90, 
                minRows: 2,
              },
            ],
          },
          {
            icon:'el-icon-info',
            label: '商品信息',
            prop: 'goodsImformation',
            column: [
              {
                label: '',
                prop: 'goods',
                span: 24,
                formslot: true,
                labelWidth: 0, 
              },
            ]
          },
        ],
      },
      cardsData: [],
      cardTableOption: {
        border: true,
        index: true, 
        indexLabel: "序号",
        stripe: true,
        align: 'center',
        menu: true,
        menuWidth: 150,
        columnBtn: false,
        refreshBtn: false,
        searchBtn: false,
        addBtn: false,        
        editBtn: false,
        delBtn: false,
        addRowBtn: true,
        cellBtn: true,
        showSummary: true,
        sumColumnList: [
          {
            label: ' ',
            name: 'orderQyt',
            type: 'sum',
            decimals: 0,
          },
          {
            label: ' ',
            name: 'totalPrice',
            type: 'sum'
          }
        ],
        column: [
           {
            type: "input",
            overHidden: true,
            label: "商品ID",
            prop: "goodsId",
            span: 24,
            hide: true,
            display: false,
          },
          {
            overHidden: true,
            label: "商品名称",
            prop: "goodsNo",
            span: 24,
            slot: true,
          },
          {
            label: '商品明细',
            prop: 'goodsSpecifications',
            children: [],
          },
          {
            type: "input",
            overHidden: true,
            label: "商品单位",
            prop: "unit",
            width: 80,
            span: 24,
          },
          {
            type: "input",
            overHidden: true,
            label: "商品价格",
            prop: "price",
            width: 80,
            span: 12,
          },
          {
            type: "input",
            overHidden: true,
            label: "商品数量",
            prop: "orderQyt",
            slot: true,
            span: 12,
          },
          {
            type: "input",
            overHidden: true,
            label: "小计",
            prop: "totalPrice",
            width: 100,
            span: 12,
          },

        ],
      },
      custNameList: [],
      goodsTypeList: [],
      goodsNoListDisabled: false,

    }
  },
  watch: {
    visible: {
      handler(newVal, oldVal) {
        if(newVal === false) {
          this.resetModalData()
        }
      }
    },
  },
  created() {
    console.log("created");
    this.resetModalData()
    this.getSelectOptions()
  },
  methods: {
    mergeFormOption() {
      this.formOption = Object.assign(this.formOption, this.selfOption)
      this.formOption.group[0].column[1].dicData = this.custNameList
    },
    async init(params, modalFlag) {
      console.log("init 参数", params);
      this.selfOption = JSON.parse(JSON.stringify(this.initSelfOption))
      this.modalFlag = modalFlag
      this.form = params
      if(params.orderNo) {
        console.log("编辑", true);
        this.form.goodsNoList = params.goodsNo
        // this.cardsData = JSON.parse(params.goods)
      } else {
        console.log("新增", false);

        await fetchList(this.url.getOrderNo).then(res => {
          this.form.orderNo = res.data.data
        }).catch(err => {
          this.$message.error("未能连上服务器获得订单号，请稍后重试！")
        })
      }
      this.visible = true
      this.mergeFormOption()
    },
    changeGoodsNoList(e) {
      this.form.goodsNoList = e
      // console.log("类型改变", e);
      if(e.length === 0) {
        this.cardsData = []
        return
      }
      if(e.length < this.cardsData.length) {
        this.cardsData.forEach((i, k) => {
          if(e.indexOf(i.goodsTypeNo) < 0) {
            this.cardsData.splice(k, 1)
          }
        })
      } else {
        e.forEach(item => {
          if(!this.cardsData.find(i => i.goodsTypeNo === item)) {
            this.addOnetoCardsData(item)
          }
        })
      }
    },

    // 点击下一步时，验证是否选择了至少一个商品
    hasGoods() {
      let sum = 0
      this.cardsData.forEach(i => {
        if(i.tableData.length && i.tableData.find(i => i.orderQyt > 0)) {
          sum++
        }
      })
      if(sum > 0) {
        return true
      } else {
        return false
      }
    },
    // 下一步
    // 处理数据
    handleSubmit(form) {
      this.$refs.formRef.validate(async (valid, done) => {
        if (!valid) return
        if(!this.hasGoods()) {
          this.$message.warning("请在商品信息中至少选择订一个商品并设置商品数量！")
          return
        }
        this.btnLoading = true

        // 处理提交给后端的数据
        let params = JSON.parse(JSON.stringify(this.form))
        if(this.modalFlag === 'add') {
          params.exWarehouseId = 0
        }
        params.goodsNameList = []
        params.goodsNoList.forEach(goodsNo => {
          params.goodsNameList.push(this.goodsTypeList.find(o => o.value === goodsNo).label)
        })
        this.form.custName = this.form.$custNo
        params.goodsNo = params.goodsNoList
        this.form.goodsNo = params.goodsNoList
        delete params.goodsNoList
        params.goodsName = params.goodsNameList
        this.form.goodsName = params.goodsNameList
        delete params.goodsNameList
        delete params.goods

        params.goodsDealList = []
        this.cardsData.forEach(i => {
          // 表格有记录行，才进行遍历
          if(i.tableData.length) {
            i.tableData.forEach(ii => {
              // 记录行有商品数量，才放入数组 temp.goodsDealList
              if(ii.orderQyt > 0) {
                let obj = {}
                obj.id = ii.id || 0
                obj.goodsNo = ii.goodsNo
                obj.goodsName = ii.goodsName
                obj.price = ii.price
                obj.unit = ii.unit
                obj.goodsType = ii.goodsType
                obj.orderQyt = ii.orderQyt
                let temp1 = {}
                i.column.forEach(iii => {
                  temp1[iii.label] = ii[iii.label] || ''
                })
                obj.goodsProp = JSON.stringify(temp1)
                params.goodsDealList.push(obj)
              }
            })
          }
        })
        console.log("===== params =====", JSON.stringify(params));

        // let url = this.modalFlag === 'add' ? this.url.addOne : this.url.editOne
      
        await addResult(this.url.addOne, params).then(res => {
          console.log(res);
          if(res.data.code === 0) {
            let msg = this.modalFlag === 'add' ? '新增订单成功！' : '修改订单成功！'
            this.$message.success(msg)
            this.$emit("ok")
          } else {
            let msg = this.modalFlag === 'add' ? '新增订单失败！原因：' : '修改订单失败！原因：'
            this.$message.warning(msg + res.data.msg)
          }
          this.btnLoading = false
          done()
        }).catch(err => {
          this.btnLoading = false
          done()
          this.$message.error("错误！原因：" + err)
        });
      })
    },
    stepPlus() {
      let obj = {}
      obj.form = this.form
      let temp = JSON.parse(JSON.stringify(this.cardsData))
      temp.forEach(i => {
        i.cardTableOption.menu = false
        i.cardTableOption.border = false
        i.cardTableOption.addRowBtn = false
        i.cardTableOption.column.forEach(ii => {
          if(ii.slot === true) {
            delete ii.slot
          }
          if(ii.prop === 'goodsSpecifications') {
            ii.children.map(iii => {
              iii.cell = false
              return iii
            })
          }
          if(ii.prop === 'goodsNo') {
            ii.prop = 'goodsName'
          }
        })
      })
      console.log("表格数据",  this.cardsData);
      obj.cardsData = temp
      this.$refs.modalViewRef.init(obj)
    },
    handleEmpty() {
      this.resetModalData()
    },

    addUpdate(form, index, done, loading) {
      form.$cellEdit = false
      loading()
    },
    handleDelete(record, index, cadrsInde) {
      this.cardsData[cadrsInde].tableData.splice(index, 1)
    },

    // 当前页面部分数据置空
    resetModalData() {
      this.form = {
        orderNo: undefined,
        custNo: undefined,
        goodsNoList: undefined,
        orderDate: undefined,
        remark: undefined,
        // logo: '/company/logo.png',
      }
      this.cardsData = []
      this.btnLoading = false
      // this.goodsTypeList = []
      // this.custNameList = []
    },
    addOnetoCardsData(val) {
      console.log("新增的类型", val, val.length, this.goodsTypeList.find(i => i.goodsTypeNo == val));
      let obj = {
        goodsTypeNo: val,
        goodName: this.goodsTypeList.find(i => i.value === val.replace(/\s*/g,"")).label,
        column: [],
        tableData: [],
        cardTableOption: JSON.parse(JSON.stringify(this.cardTableOption)),
        goodsNoList: [],
      }

      getResult(`${this.url.getGoodsTypeColumn}`, val).then(res => {
        if(res && res.data && res.data.data && res.data.data.length) {
          obj.column = res.data.data.map(i => {
            i.temp = i.prop
            i.prop = i.label
            i.cell = true
            if(i.label === '位置') {
              i.type= 'select'
              i.dicData = [
                { label: 'R', value: 'R' },
                { label: 'L', value: 'L' }
              ]
            }
            return i
          })
          obj.cardTableOption.column.find(i => i.prop === 'goodsSpecifications').children = obj.column
        } else {
          obj.cardTableOption.column.find(i => i.prop === 'goodsSpecifications').children = []
        }
      }).catch(err => {
        // console.log("getGoodsTypeColumn 接口出错了！", err);
      })

      getGoodsByGoodsType(val,this.form.custNo).then(res => {
        if(res && res.data && res.data.data && res.data.data.length) {
          obj.goodsNoList = res.data.data.map(i => {
            i.value = i.goodsNo
            i.label = i.goodsName
            return i
          })
        }
      })

      if(this.modalFlag === 'edit') {
        let temp = this.form.goodsOrderTypeVoMap.find(i => i.goodsTypeNo === val)
        obj.tableData = temp.goodsDealList.map(i => {
          i.$cellEdit = false
          if(i.goodsProp && JSON.parse(i.goodsProp) instanceof Object) {
            Object.keys(JSON.parse(i.goodsProp)).forEach(ii => {
              i[ii] = JSON.parse(i.goodsProp)[ii]
            })  
          }
          return i
        })
      } else {
        obj.tableData = [{ $cellEdit: true }]
      }
      console.log("处理好的obj", obj);
      this.cardsData.push(obj)

    },
    goodsNoChange(row, index, cardsIndex) {
      let temp = this.cardsData[cardsIndex]
      let temp1 = temp.goodsNoList.find(i => i.goodsNo === row.goodsNo)
      row = Object.assign(row, temp1)
    },
    orderQytChange(row, index) {
      row.totalPrice = (row.price * row.orderQyt).toFixed(2)
    },

    // 获得卡片表格商品属性明细
    async getGoodsTypeColumn(val) {
      await getResult(`${this.url.getGoodsTypeColumn}`, val).then(res => {
        if(res && res.data && res.data.data && res.data.data.length) {
          this.goodsTypeColumn = res.data.data
        } else {
          this.goodsTypeColumn = []
        }
      }).catch(err => {
        // console.log("getGoodsTypeColumn 接口出错了！", err);
      })
    },
    

    // 获得下拉数据
    getSelectOptions() {
      this.getGoodsTypeList()
      this.getCustNoList()
    },
    async getGoodsTypeList() {
      await fetchList(this.url.getGoodsTypeList).then(res => {
        this.goodsTypeList = res.data.data.map(i => {
          i.value = i.goodsTypeNo
          i.label = i.goodsTypeName
          return i
        })
      }).catch(err => {
        this.goodsTypeList = []
      });
    },
    async getCustNoList() {
      await fetchList(this.url.getCustNoList, {}).then(res => {
        if(res && res.data && res.data.data && res.data.data.length) {
          this.custNameList = res.data.data
        }
      })
    },


  }
}
</script>

<style>
  .goods .avue-crud__menu {
    min-height: 0px !important;
    /* display: none!important; */
  }
  .goods .avue-crud__pagination {
    padding: 0px !important;
  }
  .goods .el-card__header {
    padding: 8px 20px !important;
  }
  .goods .el-card__body {
    padding: 10px 20px !important;
  }

</style>
