<template>
  <basic-container>
    <div class="avue-crud" :style="`height:` + height">
      <el-form :disabled="view" ref="form" :model="form" label-width="120px" :rules="rules">
        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="始发仓地址" prop="province">
              <!--            <el-input v-model="form.province" placeholder="请输入省"/>-->
              <el-cascader
                :options="optioner"
                v-model="form.province"
                style="width: 100%"
                :props="{ checkStrictly: true }"
                popper-class="ca"
                @change="monitor($event, 1)"
              >
                <template #default="{ node, data }">
                  <span>{{ data.label }}</span>
                  <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                </template>
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="始发仓" prop="beginGranary">
              <!--            <el-input v-model="form.goalGranary" placeholder="请输入末端仓"/>-->
              <el-select
                style="width: 100%"
                v-model="form.beginGranary"
                filterable
                remote
                reserve-keyword
                placeholder="请输入始发仓"
                :remote-method="FnDeparture"
                :loading="loading"
              >
                <el-option
                  v-for="item in optionser"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="目的仓地址" prop="province">
              <!--            <el-input v-model="form.province" placeholder="请输入省"/>-->
              <el-cascader
                :options="optioner"
                v-model="form.provinceEnd"
                style="width: 100%"
                :props="{ checkStrictly: true }"
                popper-class="ca"
                @change="monitor"
              >
                <template #default="{ node, data }">
                  <span>{{ data.label }}</span>
                  <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                </template>
              </el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="目的仓" prop="goalGranary">
              <!--            <el-input v-model="form.goalGranary" placeholder="请输入末端仓"/>-->
              <el-select
                style="width: 100%"
                v-model="form.goalGranary"
                filterable
                remote
                reserve-keyword
                placeholder="请输入目的仓"
                :remote-method="remoteMethodBin"
                :loading="loading"
              >
                <el-option
                  v-for="item in goalSer"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="货物类型" prop="brand">
              <el-cascader
                :props="propsType"
                style="width: 100%"
                v-model="form.brand"
              ></el-cascader>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="费用类型" prop="freightMark">
              <el-checkbox-group class="el_chexk_flex" v-model="form.freightMark" @change="handleCheckedCitiesChange">
                <el-checkbox
                  class="el_chexk_item"
                  style="margin-bottom: 3%"
                  v-for="(item, index) in clientType"
                  :key="item.dictKey"
                  :label="item.dictKey"
                  >{{ item.dictValue }}
                  <el-input
                    type="number"
                    v-model="item.remark"
                    placeholder="请输入费用"
                    :disabled="this.form?.freightMark?.indexOf(item.dictKey) == -1"
                    @change="textbox($event,index)"
                  />
                  <el-select clearable v-model="item.identification" @change="optunit($event,index)"  placeholder="请选择单位"   style="width: 100px">
                    <el-option
                      v-for="item in optionsunit"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-checkbox>

               
              </el-checkbox-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 表单字段 -->
      </el-form>
      <!-- 表单按钮 -->
      <!-- foot -->
      <div class="foot" v-if="!view">
        <div class="dialog-footer">
          <el-button type="primary" icon="el-icon-circle-check" @click="handleSubmit('form')"
            >提 交</el-button
          >
          <!--          <el-button icon="el-icon-circle-close" @click="box = false">取 消</el-button>-->
        </div>
      </div>
    </div>
  </basic-container>
</template>

<script>
import {
  getList,
  getDetail,
  add,
  update,
  remove,
  getDetailOwn,
} from '@/api/basicdata/basicZonePrice';
import { getListBinName } from '@/api/basicdata/basicdataWarehouse';
import { getListName } from '@/api/basicdata/basicBrand';
import option from '@/option/basicdata/basicZonePrice';
import { mapGetters } from 'vuex';
import { getLazyTreeAll } from '@/api/base/region';
import { getDictionaryBiz } from '@/api/system/dict';
import { getListCopy } from '@/api/basicdata/basicdataWarehouse';
import { getListCo, getDeptLazyTree } from '@/api/basicdata/basicdataCategory';

export default {
  name: 'basicZonePriceFrom',
  data() {
    return {

      UnitList:[],//单位列表
      optionsunit:[{
        label:'件',
        value:'1',
      },
      {
        label:'方',
        value:'2',
      },
      {
        label:'公斤',
        value:'3',
      }],
      // 分页信息
      page: {
        currentPage: 1,
        pageSize: 30,
        total: 40,
      },
      propsType: {
        lazy: true,
        lazyLoad(node, resolve) {
          const { level } = node;
          setTimeout(async () => {
            // console.log("node/////////",node);
            const parentId = node.level === 0 ? 1 : node.data.value;
            // console.log("par",parentId);
            let shuju = await getDeptLazyTree(parentId);
            // console.log(")))))))))))",shuju);
            const nodes = Array.from(shuju.data.data).map(item => ({
              value: item.id,
              label: item.title,
              leaf: !item.hasChildren,
            }));

            // console.log("////////////",nodes);
            // 通过调用resolve将子节点数据返回，通知组件数据加载完成
            resolve(nodes);
          }, 500);
        },
      },
      optionProps: {
        value: 'id',
        label: 'cName',
        children: 'childrenList', //子元素字段名
        emitPath: false,
        checkStrictly: true,
        expandTrigger: 'hover', //设置鼠标悬浮展开，如果点击展开的话，会出现点击父节点后选择器直接关闭，不能选择子节点了
      },
      treeId: '',
      cascaderKey: 1, //防止搜索选项清空数据后出现报错,在加载级联选择器数据的时候+1
      height: 0,
      // 弹框标题
      title: '',
      costCorrelationId: '',
      // 是否展示弹框
      box: false,
      // 是否展示抽屉
      drawer: false,
      // 抽屉方向
      direction: 'rtl',
      // 是否显示查询
      search: true,
      // 加载中
      loading: true,
      // 是否为查看模式
      view: false,
      // 查询信息
      query: {},
      clientType: [], //字典
      wareType: [], //字典
      costList: [], //字典
      costListName: [], //字典
      costWraeList: [], //字典
      costWraeListName: [], //字典

      // 表单数据
      form: {},
      freightMark: [], //费用
      pan: false,
      // 选择行
      selectionList: [],
      // 表单配置
      option: option,
      // 表单列表
      data: [],
      optioner: [], //始发仓地址
      optionsr: [], //品牌
      optionser: [], //始发仓
      goalSer: [], //目的仓
      rules: {
        province: [
          { required: true, message: '请选择地址', trigger: 'blur' },
          // { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        brand: [{ required: true, message: '请选择品牌', trigger: 'change' }],
        freightMark: [{ required: true, message: '请选择费用类型', trigger: 'blur' }],
        cost: [{ required: true, message: '请输入费用', trigger: 'blur' }],
        warehousingTimeStatus: [{ required: true, message: '请选择时间段', trigger: 'change' }],
        warehousingTimeCharge: [{ required: true, message: '请选择时间段费用', trigger: 'blur' }],
        goalGranary: [{ required: true, message: '请选择目的仓', trigger: 'blur' }],
        beginGranary: [{ required: true, message: '请选择始发仓', trigger: 'blur' }],
      },
    };
  },
  watch: {
    'form.province'() {
      // console.log("监听到了====");
      if (this.$refs.refHandle) {
        this.$refs.refHandle.dropDownVisible = false; //监听值发生变化就关闭它
      }
    },
  },
  created() {
    getLazyTreeAll().then(res => {
      if (res.data.success) {
        this.optioner = res.data.data;
        this.onLoad(this.page);
      }
    });
    console.log('this.$route.query.type', this.$route.query.type);
    if (this.$route.query.type == 0) {
    } else if (this.$route.query.type == 1) {
      //查看
      this.handleView(this.$route.query.id);
    } else if (this.$route.query.type == 2) {
      //修改
      this.handleEdit(this.$route.query.id);
    }
  },
  mounted() {
    this.init();
  },
  computed: {
    ...mapGetters(['permission', 'tagWel', 'tagList']),
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
  },
  methods: {
    //关闭浮层
    hideCascaderInp() {
      this.$refs.cascaderRef.value.togglePopperVisible(false);
    },
    handleDrawerClose() {
      this.costCorrelationId = '';
      this.drawer = false;
    },
    handleDrawer(row) {
      this.costCorrelationId = row.id;
      this.drawer = true;
    },
    textWarebox(e, index) {
      this.costWraeList[index] = e;
    },
    textbox(e, index) {
      console.log('e,index', e, index);
      this.costList[index + 1] = e;
      console.log(this.costList);
    },
    optunit(e,index){
      this.UnitList[index + 1]= e
      console.log(this.UnitList,'this.UnitList');
      console.log(e,index);
    },
    handleCheckedCities(value) {
      if (value.length < 1) {
        this.costWraeList = [];
      }
      this.wareType.forEach(i => {
        if (value.includes(i.dictValue)) {
          // console.log(i);
          i.pitch = true;
          // this.$set(i,'pitch',false);
          this.costWraeListName = value;
        } else {
          i.pitch = false;
          this.costWraeList[i] = null;
          i.remark = null;
        }
      });
      // let checkedCount = value.length;
      // this.checkAll = checkedCount === this.cities.length;
      // this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
    },
    handleCheckedCitiesChange(value) {
      console.log('>>>>>>>', value);
      if (value.length < 1) {
        this.costList = [];
        this.costListName = [];
      }
      this.clientType.forEach(i => {
        // console.log("value.includes(i.dictkey)",value,i.dictKey);
        if (value.includes(i.dictKey)) {
          console.log(i);
          i.pitch = true;
          this.costListName = value;
          // console.log(this.costListName);
          // this.$set(i,'pitch',false);
        }
        // else{
        //   console.log("123");
        //   i.pitch = false;
        //   this.costList[i] = null;
        //   i.remark = null;
        // }
      });
      // let checkedCount = value.length;
      // this.checkAll = checkedCount === this.cities.length;
      // this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
    },
    remoteMethod(query) {
      if (query) {
        this.loading = true;
        setTimeout(async () => {
          this.loading = false;
          let list = await getListName(this.page.currentPage, this.page.pageSize, {
            brandName: query,
          });
          this.optionsr = list.data.data.records.filter(item => {
            return item.brandName.toLowerCase().includes(query.toLowerCase());
          });
        }, 200);
      } else {
        this.optionsr = [];
      }
    },
    monitor(row, num) {
      // console.log("执行了===",row,num);
      this.warehouse(row, num);
    },
    //查询始发仓库
    async warehouse(row, num) {
      console.log(num, 'num');
      let a = {
        province_code: row.length > 0 ? row[0] : null,
        city_code: row.length > 1 ? row[1] : null,
        code: row.length > 2 ? row[1] : null,
      };
      let co = await getListCopy(this.page.currentPage, this.page.pageSize, a);
      if (num == 1) {
        this.optionser = co.data.data.records;
        console.log(this.optionser, '始发仓数据');
      } else {
        this.goalSer = co.data.data.records;
      }
    },
    // 始发仓库下拉
    FnDeparture(query) {
      if (query) {
        this.loading = true;
        setTimeout(async () => {
          this.loading = false;
          let list = await getListBinName(this.page.currentPage, this.page.pageSize, {
            name: query,
          });
          console.log(list, 'list');
          this.optionser = list.data.data.records.filter(item => {
            console.log('this.optionser', this.optionser);
            return item.name.toLowerCase().includes(query.toLowerCase());
          });
        }, 200);
      } else {
        this.optionser = [];
      }
    },
    // 目的仓库下拉
    remoteMethodBin(query) {
      if (query) {
        this.loading = true;
        setTimeout(async () => {
          this.loading = false;
          let list = await getListBinName(this.page.currentPage, this.page.pageSize, {
            name: query,
          });
          console.log(list, 'list');
          this.goalSer = list.data.data.records.filter(item => {
            console.log('this.goalGranary', this.goalSer);
            return item.name.toLowerCase().includes(query.toLowerCase());
          });
        }, 200);
      } else {
        this.goalSer = [];
      }
    },
    init() {
      this.height = this.setPx(document.body.clientHeight - 155);
      //字典
      getDictionaryBiz('jg_freight_mark').then(res => {
        // console.log("字典》》》",res);
        this.clientType = res.data.data;
      });
      //字典
      // getDictionaryBiz('warehousing_time_status').then(res => {
      //   // console.log("字典》》》",res);
      //   this.wareType = res.data.data;
      // });
    },
    searchHide() {
      this.search = !this.search;
    },
    searchChange() {
      this.onLoad(this.page);
    },
    searchReset() {
      this.query = {};
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },
    bianLier(costListName, clientType, costList, fei) {
      console.log('>>>>>>>>>', costListName, clientType, costList, fei);
      this.pan = false;
      // fei = [];
      for (let i = 0; i < costListName.length; i++) {
        if (!costList) {
          this.pan = true;
          return;
        }
        for (let a = 0; a < clientType.length; a++) {
          // console.log("进来了",clientType[a].dictKey , costListName[i]);
          if (clientType[a].dictKey == costListName[i]) {
            console.log('进来了', clientType[a].dictKey, costListName[i]);
            let zhi = costList[costListName[i]];
            if (!zhi) {
              this.pan = true;
              continue;
            } else {
              //2.添加
              fei.set(clientType[a].dictKey, zhi);
            }
          }
        }
      }
    },
    handleSubmit(from) {
      console.log(this.form, 'this.form');
      this.$refs[from].validate(async valid => {
        if (valid) {
          if (!this.form.id) {
            let fei = new Map();
            await this.bianLier(this.costListName, this.clientType, this.costList, fei);
            this.form.fei = Object.fromEntries(fei);
            this.form.freightMark = undefined;
            console.log(this.from, '当前表单的值');

            if (this.pan) {
              console.log(this.pan,'this.pan');
              this.$message.warning('请填写完整已勾选的数据费用');
              return;
            }
            this.form.city = this.form.province[1];
            this.form.district = this.form.province[2];
            this.form.province = this.form.province[0];
            this.form.cityEnd = this.form.provinceEnd[1];
            this.form.districtEnd = this.form.provinceEnd[2];
            this.form.provinceEnd = this.form.provinceEnd[0];
            this.form.brandList = this.form.brand.join(',');
            this.form.brand = this.form.brand[this.form.brand.length - 1];
            this.form.identification = {};
            this.UnitList.forEach((item, index) => {
            const key = index;
             this.form.identification[key] = item[Object.keys(item)[0]];
            });
            console.log('提交的数据》》》', this.form);
            add(this.form).then(() => {
              this.box = false;
              this.onLoad(this.page);
              this.$message({
                type: 'success',
                message: '操作成功!',
              });
              this.contextmenuFlag = false;
              this.$store.commit('DEL_TAG_CURRENT'); //关闭当前页面
              this.$router.push('/basicdata/brand/basicZonePrice'); //添加成功跳转到列表
              // this.$router.push(this.tagWel);
              console.log('执行了新增操作');
            });
          } else {
            let fe = new Map();
            await this.bianLier(this.costListName, this.clientType, this.costList, fe);
            this.form.fei = Object.fromEntries(fe);
            this.form.city = this.form.province[1];
            this.form.district = this.form.province[2];
            this.form.province = this.form.province[0];
            this.form.cityEnd = this.form.provinceEnd[1];
            this.form.districtEnd = this.form.provinceEnd[2];
            this.form.provinceEnd = this.form.provinceEnd[0];
            if (JSON.stringify(this.form.goalGranary).length < 15) {
              this.form.goalGranary = null;
            }
            if (JSON.stringify(this.form.beginGranary).length < 15) {
              this.form.beginGranary = null;
            }
            this.form.brand = this.form.brand[this.form.brand.length - 1];
            this.form.freightMark = null;
            console.log('====>>>', this.form);
            update(this.form).then(() => {
              this.box = false;
              this.onLoad(this.page);
              this.$message({
                type: 'success',
                message: '操作成功!',
              });
              this.contextmenuFlag = false;
              console.log('执行了编辑操作');
              this.$store.commit('DEL_TAG_CURRENT');
              this.$router.push('/basicdata/brand/basicZonePrice'); //添加成功跳转到列表

              // this.$router.push(this.tagWel);
            });
          }
        }
      });
    },
    handleAdd() {
      // this.title = '新增'
      // this.form = {}
      // this.init ();
      // this.box = true;
      this.$router.push({
        path: '/basicdata/brand/basicZonePriceFrom',
        query: {
          id: '',
          name: '新增',
        },
      });
    },
    handleEdit(row) {
      this.title = '编辑';
      this.box = true;
      getDetailOwn(row).then(res => {
        // console.log("dada",res.data.data);
        this.form = res.data.data;
        let a = [];
        let b = [];
        if (!!this.form.province) {
          a.push(res.data.data.province);
          a.push(res.data.data.city);
          a.push(res.data.data.district);
        }
        if (!!this.form.province) {
          b.push(res.data.data.provinceEnd);
          b.push(res.data.data.cityEnd);
          b.push(res.data.data.districtEnd);
        }
        this.form.province = a;
        this.form.provinceEnd = b;
        this.form.beginGranary = this.form.beginName;
        this.form.goalGranary = this.form.endName;
        this.form.brand = this.form.brandList.split(',');
        let sb = [];
        this.form.fei.forEach(it => {
          this.clientType.forEach(i => {
            if (it.coding == i.dictKey) {
              const value = parseFloat(it.ensue).toFixed(2);
              i.remark = value.substring(0, value.lastIndexOf('.') + 3);
              this.costList[it.coding] = i.remark;
            }
          });
          sb.push(it.coding);
        });
        this.form.freightMark = sb;
        this.costListName = sb;
      });
    },
    handleView(row) {
      // console.log("row>>>>>>>>",row);
      this.view = true;
      getDetailOwn(row).then(res => {
        console.log('执行了这个');
        this.form = res.data.data;
        // console.log(" res.data.data;",res.data.data);
        let a = [];
        let b = [];
        if (!!this.form.province) {
          a.push(res.data.data.province);
          a.push(res.data.data.city);
          a.push(res.data.data.district);
        }
        if (!!this.form.province) {
          b.push(res.data.data.provinceEnd);
          b.push(res.data.data.cityEnd);
          b.push(res.data.data.districtEnd);
        }
        this.form.province = a;
        this.form.provinceEnd = b;
        this.form.beginGranary = this.form.beginName;
        this.form.goalGranary = this.form.endName;
        this.form.brand = this.form.brandList.split(',');
        let sb = [];
        // this.form.fei.forEach( it =>{
        //   this.clientType.forEach( i => {
        //     if(it.coding == i.dictKey){
        //       i.remark = it.ensue.substring(0,it.ensue.lastIndexOf("."))
        //     }
        //   })
        //   sb.push(it.coding);
        // })

        this.form.fei.forEach(it => {
          this.clientType.forEach(i => {
            if (it.coding == i.dictKey) {
              const value = parseFloat(it.ensue).toFixed(2);
              i.remark = value.substring(0, value.lastIndexOf('.') + 3);
              this.costList[it.coding] = i.remark;
            }
          });
          sb.push(it.coding);
        });

        this.form.freightMark = sb;
      });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.selectionClear();
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!',
          });
        });
    },
    beforeClose(done) {
      done();
      this.form = {};
      this.view = false;
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      // this.$refs.table.clearSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page);
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      if (!!this.query.province) {
        this.query.city = this.query.province[1];
        this.query.district = this.query.province[2];
        this.query.province = this.query.province[0];
      }
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.clientType.forEach(it => {
          data.records.forEach(i => {
            if (parseInt(it.dictKey) == parseInt(i.freightMark)) {
              i.freightMark = it.dictValue;
            }
            if (i.freightMark == '-1') {
              i.freightMark = '无';
            }
          });
        });
        // this.wareType.forEach(it =>{
        //   data.records.forEach(i =>{
        //     if(parseInt( it.dictKey ) == parseInt(i.warehousingTimeStatus)){
        //       i.warehousingTimeStatus = it.dictValue
        //     }
        //     if(i.warehousingTimeStatus == '-1'){
        //       i.warehousingTimeStatus = '无'
        //     }
        //   })
        // })
        this.page.total = data.total;
        this.data = data.records;
        let dz = '';
        console.log('this.optioner>>>>>>>>data.records>>>>>>');
        data.records.forEach(it => {
          let arrsheng = this.optioner.filter(i => {
            return it.province == i.value;
          });
          // console.log("========",JSON.parse(JSON.stringify(arrsheng)) );
          let arrshi = arrsheng[0].children.filter(i => {
            return it.city == i.value;
          });
          // console.log("========",JSON.parse(JSON.stringify(arrsheng)) );
          let arrqu = arrshi[0].children.filter(i => {
            return it.district == i.value;
          });
          // console.log("========",JSON.parse(JSON.stringify(arrsheng)) );
          dz = arrsheng[0].label + '/' + arrshi[0].label + '/' + arrqu[0].label;
          it.province = dz;
        });
        this.loading = false;
        this.selectionClear();
      });
    },
  },
};
</script>
<style lang="scss">
.foot {
  position: fixed;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 999;
  height: 60px;
}
.foot .dialog-footer {
  margin-bottom: 130px;
  text-align: center;
}
.ca .el-radio__inner {
  top: -18px;
  left: -19px;
  border-radius: 0;
  border: 0;
  width: 170px;
  height: 34px;
  background-color: transparent;
  cursor: pointer;
  box-sizing: border-box;
  position: absolute;
}

.ca .el-radio__input.is-checked .el-radio__inner {
  background: transparent;
}
.el_chexk_flex{
  width: 100%;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    .el_chexk_item{
      width: 18%;
    }


}
.el_chexk_item{
  width: 20%;
  .el-checkbox__label{
      width: 100%;
      .el-input{
      width: 100%;
    }
    }
    margin-right: 12%;
}
</style>
